Converting a numeric value to time in R [duplicate] - r

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))

Related

Handling time variables in R for ANOVA

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))

Converting integer format date to double format of date

I have date format in following format in a data frame:
Jan-85
Apr-99
1-Nov
Feb-96
When I see the typeof(df$col) I get the answer as "integer".
Actually when I see the format in excel it is in m/d/yyyy format. I was trying to convert this to date format in R. All my efforts yielded NA.
I tried parse_date_time function. I tried as.date along with as.character. I tried as.POSIXct but everything is giving me NA.
My trials were as follows and everything was a failure:
as.Date.numeric(df$col,"m%d%Y")
transform(df$col, as.Date(as.character(df$col), "%m%d%Y"))
as.Date(df$col,"m%d%Y")
as.POSIXct.numeric(as.character(loan_new$issue_d), format="%Y%m%d")
as.POSIXct.date(as.character(df$col), format="%Y%m%d")
mdy(df$col)
parse_date_time(df$col,c("mdy"))
How can I convert this to date format? I have used lubridate package for parse_date_time and mdy package.
dput output is below
Label <- factor(c("Apr-08",
"Apr-09", "Apr-10", "Apr-11", "Aug-07", "Aug-08", "Aug-09", "Aug-10",
"Aug-11", "Dec-07", "Dec-08", "Dec-09", "Dec-10", "Dec-11", "Feb-08",
"Feb-09", "Feb-10", "Feb-11", "Jan-08", "Jan-09", "Jan-10", "Jan-11",
"Jul-07", "Jul-08", "Jul-09", "Jul-10", "Jul-11", "Jun-07", "Jun-08",
"Jun-09", "Jun-10", "Jun-11", "Mar-08", "Mar-09", "Mar-10", "Mar-11",
"May-08", "May-09", "May-10", "May-11", "Nov-07", "Nov-08", "Nov-09",
"Nov-10", "Nov-11", "Oct-07", "Oct-08", "Oct-09", "Oct-10", "Oct-11",
"Sep-07", "Sep-08", "Sep-09", "Sep-10", "Sep-11"))
NA is typically what you get when you misspecify the format. Which is what you do. That said, if your data is really looking like the first example you gave, it's impossible to simply convert this to a date. You have two different formats, one being month-year and the other day-month.
If your updated date (i.e. Dec-11) is the correct format, then you use the format argument of as.Date like this:
date <- "Dec-11"
as.Date(date, format = "%b-%d")
# [1] "2017-12-11"
Or on your example data:
as.Date(Label, format = "%b-%d")
# [1] "2017-04-08" "2017-04-09" "2017-04-10" "2017-04-11" "2017-08-07" "2017-08-08"
# [7] "2017-08-09" "2017-08-10" "2017-08-11" "2017-12-07" "2017-12-08" "2017-12-09"
If you want to convert something like Jan-85, you have to decide which day of the month that date should have. Say we just take the first of each month, then you can do:
x <- "Jan-85"
xd <- paste0("1-",x)
as.Date(xd, "%d-%b-%y")
# [1] "1985-01-01"
More information on the format codes can be found on ?strptime
Note that R will automatically add this year as the year. It has to, otherwise it can't specify the date. In case you do not have a day of the month (eg like Jan-85), conversion to a date is impossible because the underlying POSIX algorithms don't have all necessary information.
Also keep in mind that this only works when your locale is set to english. Otherwise you have a big chance your OS won't recognize the month abbreviations correctly. To do so, do eg:
Sys.setlocale(category = "LC_TIME", locale = "English_United Kingdom")
You can later set it back to the original one if you must, or restart your R session to reset the locale settings.
note: Please check carefully which locale notations are valid for your OS. The above example works on Windows, but is not guaranteed on either Linux or Mac.
Why you see integer
The fact that these string values are of integer type, is due to the fact that R automatically convert character vectors to factors when reading in a data frame. So typeof() returns integer because that's the internal representation of a factor.

Obtain Time format from a String

I am getting Data where the first column is always a string with the Time like
Time <- "2015-06-01 09:45:33"
for plotting, later I convert it with as.POSIXct and so on.
But sometimes I have another Time string like
Time <- "2015/07/01 09:33"
So is there a possibility(or a function) to check the Time format of the string in a way like this
format <- checkFormat(Time)
and then convert it automatically to
as.POSIXct(Time, format=format)
I cant be the first one who asks this, although i really searched a lot.
Thanks
As requested in answer format: it is not possible, since in your example no solution can know if 06 is the month and 01 the day or vice versa.
You can change the time format string with
Time <- "2015/07/01 09:33"
Time <- if(grepl("\\d{4}/\\d{2}/\\d{2}", Time)) gsub("/", "-", Time)

Extract dates times from a data.frame in R

I have a dataset with some date time like this "{datetime:2015-07-01 09:10:00" So I wanted to remove the text, and then keep the date & the time as as.Date returns only the date. So I write this code but the only problem I have is that during the second line with strsplit, it only returns me the date time of the first line and so erase the others... I woud love to get ALL my date time not only the first. I thought about sapply maybe, but I can't make it right I have many errors or maybe with a loop for? I am novice to R so I don't really know how to do this the best way.
Could you help me please? Besides If you have another idea for the time & date format or a simple way to do it, it should be very nice of you too.
data$`Date Time`=as.character(data$`Date Time`)
data$`Date Time`=unlist(strsplit(data[,1], split='e:'))[2]
date=substr(data$`Date Time`,0,10)
date=as.Date(date)
time=substr(data$`Date Time`,12,19)
data$Date=date
data$Time=time
Thank you very much for your help!
You could use the format argument to avoid all the strsplit:
times <- as.POSIXct(data$`Date Time`, format='{datetime:%Y-%m-%d %H:%M:%S')
(The reason for the "{datetime:" in the format is because you mentioned this is the format of your strings).
This object has both date and time in it, and then you can just store it in the dataframe as a single column of type POSIXct rather than two columns of type string e.g.
data$datetime <- times
but if you do want to store the date as a Date and the time as a string (as in your example above):
data$Date <- as.Date(times)
data$Time <- strftime(times, format='%H:%M:%S')
See ?as.Date, ?as.POSIXct, ?strptime for more details on that format argument and various conversions between date and string.

Writing a function with date and time

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

Resources