not_a_robot not_a_robot - 2 months ago 12
R Question

Dealing with numeric (decimal) dates in R?

I have some numeric date data from Excel:

> df <- data.frame(c(42613, 42612, 42614), c(42614.61, 42613.97, 42612.12))
> names(df) <- c("Closetime", "Opentime")


Both
Closetime
and
Opentime
are
numeric
. I want to preserve the hour/minute/second data from
OpenTime
and add the time '00:00:00' to every date in
Closetime
:

> df$Closetime <- paste(as.Date(df$Closetime, origin = '1900-01-01'), c('00:00:00'))


Easy enough to do
Closetime
, but when I try using
lubridate::date_decimal
on
Opentime
, everything goes to hell.

> df$Opentime <- date_decimal(df$Opentime)
> df
Closetime Opentime
1 2016-09-02 00:00:00 42614-08-11 15:36:00
2 2016-09-01 00:00:00 42613-12-21 01:12:00
3 2016-09-03 00:00:00 42612-02-13 22:04:48


How can I get both
Opentime
and
Closetime
to be of the same type/format? I am eventually looking to be able to get the difference, in hours, between the times in each column, for reference.

Answer

If you can use POSIXct, you can do for example

df$Opentime <- as.POSIXct( df$Opentime*24*60*60, 
                origin="1900-01-01", 
                tz="UTC")

Reasoning: POSIXct is just number of seconds since origin