I am new to R and programming in general and am looking for help with writing a function with dates and times. I have checked around but am still a bit stuck.
Basically, I have dates in the format "dd/mm/YYYY HH:MM" and I have to calculate how much time has passed between various events.
I have given the following command (where "date" is the column in my data frame that indicates the date and time in the above format):
date=as.Date.factor(date,format="%d/%m/%Y %H:%M")
However, this displays only the date, without the time.
I also have tried:
date=substr(argo1$date,1,907)
And it shows the date and time.
However, when I try to find the difference between two dates i.e.the time that has passed with the command: difftime(date[2],date[3],unit="secs"), it returns that 0 seconds have passed.
When I try to find the difference with the command:
date[3]-date[2]
it tells me
Error in date[3] - date[2] : non-numeric argument to binary operator
The class(date) is "character".
Any idea what I am doing wrong?
Try strptime:
date1 = "30/12/2009 11:59"
date2 = "30/12/2009 12:03"
d1 = strptime(date1, "%d/%m/%Y %H:%M")
d2 = strptime(date2, "%d/%m/%Y %H:%M")
difftime(d1, d2, unit="secs")
# Time difference of -240 secs
Related
As the title suggests, I am trying to use either lubridate or ANYTIME (or similar) to convert a time from 24 hour into 12 hour.. To make life easier I don't need the whole time converted.
What I mean is I have a column of dates in this format:
2021-02-15 16:30:33
I can use inbound$Hour <- hour(inbound$Timestamp) to grab just the hour from the Timestamp which is great.. except that it is still in 24hr time. (this creates an integer column for the hour number)
I have tried several mutates such as inbound <- inbound %>% mutate(Hour = ifelse(Hour > 12, sum(Hour - 12),Hour)
This technically works.. but I get some really wonky values (I get a -294 in several rows for example)..
is there an easier way to get the 12hr time converted?
Per recommendation below I tried to use a base FORMAT as follows:
inbound$Time <- format(inbound$Timestamp, "%H:%M:%S")
inbound$Time <- format(inbound$Time, "%I:%M:%S")
and on the second format I am getting an error
Error in format.default(inbound$Time, "%I:%M:%S") :
invalid 'trim' argument
I did notice the first format converts to a class CHARACTER column.. not sure if that is causing issues with the 2nd format or not..
I then also tried:
`inbound$time <- format(strptime(inbound$Timestamp, "%H:%M:%S"), "%I:%M %p")`
Which runs without error.. but it creates a full column of NA's
Final edit::::: I made the mistake of mis-reading/applying the solution and that caused errors.. when using the inbound$Time <- format(inbound$Time, "%I:%M:%S") or as.numeric(format(inbound$Timestamp, "%I")) from the comments... both worked and solved the issue I was having.
To be clear... From 2021-02-15 16:30:33 you want just 04:30:33 as a result?
No need for lubridate or anytime. Assuming that is a Posixct
a <- as.POSIXct("2021-02-15 16:30:33")
a
# [1] "2021-02-15 16:30:33 UTC"
b <- format(a, "%H:%M:%S")
b
#[1] "16:30:33"
c <- format(a, "%I:%M:%S")
c
#[1] "04:30:33"
im relatively new to R. I´m doing an experiment where i measure the exact time where a couple of insects mate in 14 days in different luminic conditions (12:12H Light/Dark, Continious light, Continious dark).The idea is to analyze this data with ANOVA, but i'm having problems with the data. So I have a .csv file with 3 columns: Light condition, Date and Time. Date is not required for the analysis so i dont need it. But i have trouble converting the time data for a proper data R can work with. I've already tried read.csv(file="",stringsAsFactors = FALSE) but it doesnt work at all, I've also tried with lubridate , as.POSIX function and strptime() but nothing seems to work (or maybe im not converting the data at all for a proper analysis)
Thank you in advance.
It looks like you have date and time in two different columns and for time you have only hour and minutes. You can combine them using paste and convert to date time using appropriate format.
df$DateTime <- as.POSIXct(paste(df$Dia, df$Hora),
format = "%Y-%m-%d %H:%M",tz = "UTC")
#Can also use strptime
df$DateTime <- strptime(paste(df$Dia, df$Hora),
format = "%Y-%m-%d %H:%M", tz = "UTC")
Or with lubridate
df$DateTime <- lubridate::ymd_hm(paste(df$Dia, df$Hora))
I have data below for work hours which I need to compare - start and stop with date and time. I first extract the time portion of each as start and stop variables, then use the chron package to change them from factor data to something I can compare more easily.
require(chron)
eg_data3 <- data.frame(
id = c('42', '42', '42', '42', '42'),
time_in = as.factor(c('11/5/2017 13:52', '11/4/2017 14:25', '11/5/2017 15:30', '11/5/2017 17:10', '11/6/2017 18:20')),
time_out = as.factor(c('11/5/2017 13:59', '11/4/2017 14:59', '11/5/2017 16:00', '11/5/2017 17:45', '11/6/2017 18:50')))
eg_data3$start_time <- substring(strptime(eg_data3$time_in, format = "%m/%d/%Y %H:%M"),12,19)
eg_data3$end_time <- substring(strptime(eg_data3$time_out, format = "%m/%d/%Y %H:%M"),12,19)
eg_data3$end_time <- chron(times = eg_data3$end_time)
eg_data3$start_time <- chron(times = eg_data3$start_time)
Next, I generate another variable which compares the difference between stop time 1, and start time 2, IE stop time in row 1 with start time in row 2, to see the gap between them.
require(dplyr)
eg_data3 <- eg_data3 %>% group_by(id) %>% mutate(diff_outX0_inX1 = start_time - lag(end_time))
When I do this, the variable is formatted as a decimal. I cannot for the life of me get it to display as hh:mm:ss. I have tried specifying out.format as hh:mm:ss in chron, changing time_in / time_out to numeric and character before and after extraction and applying chron(times), changing the format of the diff_ variable after, etc.
What seems like a very simple question -
How do I get the result comparison (diff_outX0_inX1) variable to display as time, either hh:mm or hh:mm:ss ?? I know the formula to convert fractional days into minutes in Excel, but I'd prefer to not write out a two step function, I assume it's a simple formatting issue.
Any help is appreciated.
EDIT - got flagged as a duplicate...OK. I asked if there was a way to do this that did not involve writing a function. The answer that was linked involves a function. First comment provided a clean simple answer. I can reproduce the answer in the comment, I could not reproduce the function myself, not nearly as helpful. I also added another solution that does not requre dplyr. No where I looked online showed me something as simple as "just format the result with chron."
I was trying this piece of code in R about data-time formats in one of the online courses. It gives me the required output but I am unable to figure out how it works, especially the referencing a function name with the same function.
str2 <- "2012-3-12 14:23:08"
# Convert the strings to POSIXct objects: time2
time2 = as.POSIXct(str2, format = "%Y-%m-%d %H:%M:%S")
# Convert times to formatted strings: Confusion over this piece of code format within format
format(time2, format="%H hours: %M minutes %p")
The output is "14 hours: 23 minutes PM", which is fine. But, I am unable to figure out the syntax of how format within format works. Can anyone please help?
format is a generic function. The correct method will be called based on the class of the object passed as the first argent. For POSIXct objects the method format.POSIXct will be called.
?format.POSIXct shows it accepts the format argument.
I have a data frame containing what should be a datetime column that has been read into R. The time values are appearing as numeric time as seen in the below data example. I would like to convert these into datetime POSIXct or POSIXlt format, so that date and time can be viewed.
tdat <- c(974424L, 974430L, 974436L, 974442L, 974448L, 974454L, 974460L, 974466L, 974472L,
974478L, 974484L, 974490L, 974496L, 974502L, 974508L, 974514L, 974520L, 974526L,
974532L,974538L)
974424 should equate to 00:00:00 01/03/2011, but the do not know the origin time of the numeric values (i.e. 1970-01-01 used below does not work). I have tried using commands such as the below to achieve this and have spent time trying to get as.POXISct to work, but I haven’t found a solution (i.e. I either end up with a POSIXct object of NAs or end up with obscure datetime values).
Attempts to convert numeric time to datetime:
datetime <- as.POSIXct(strptime(time, format = "%d/%m/%Y %H:%M:%S"))
datetime <- as.POSIXct(as.numeric(time), origin='1970-01-01')
I am sure that this is a simple thing to do. Any help would be greatly received. Thanks!
Try one of these depending on which time zone you want:
t.gmt <- as.POSIXct(3600 * (tdat - 974424), origin = '2011-03-01', tz = "GMT")
t.local <- as.POSIXct(format(t.gmt))