Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert fraction of day to POSIX times in R [duplicate]

Tags:

datetime

r

excel

I have a dataset that encodes a date-time into two separate variables. Normally, I'd just paste them together inside of an as.POSIXct and carry on. However, the date is provided as a string, and the time of day as a fraction of 24 hours - e.g., 12pm is 0.5, 9:30am is 0.1458333, etc.

It doesn't seem all that tricky to convert the fractional days into clock hours, but I'd prefer to use a pre-existing function if possible. Does something like that exist in base R? A package?

If it's any use, this is an Excel (xlsx) time field imported into R through RODBC.

EDIT Oddly enough, upon revisiting this problem, the times are now read in as POSIXct. Not sure what to make of that.

like image 431
Matt Parker Avatar asked Feb 01 '11 22:02

Matt Parker


2 Answers

The R News 4/1 Help Desk article has a section on reading Excel dates in R.

like image 102
G. Grothendieck Avatar answered Nov 09 '22 14:11

G. Grothendieck


POSIXct values are simply the number of seconds since midnight GMT 1970-01-01. (So you need to pay attention to your offset from UTC.) You can use the date part and add the number of days times 24*3600 (as.Date(dtval) to your time value * 24*3600. Gabor pointed to the article in R News (which he wrote, thank you, Gabor.)

You didn't give an example of the string. If you are getting your date as a string, then as.Date(strDate) will convert a variable "strDate" to Date class when it is in either "YYYY-MM-DD" or "YYYY/MM/DD" format. Otherwise the formatting codes are on the ?strptime page.

Once you have a POSIXct-classed variable you can just add the number of seconds. This example add 30 minutes to midnight today Feb 1, 2011 (in my time zone which is UTC-5):

> as.POSIXct(as.Date("2011-02-01")) +30*60
[1] "2011-01-31 19:30:00 EST"

And this is your time value added to midnight my time:

> as.POSIXct(as.Date("2011-02-01 00:00", tzone="UTC"))+3600*5 + 3600*24*timeval
[1] "2011-02-01 03:29:59 EST"
like image 5
IRTFM Avatar answered Nov 09 '22 15:11

IRTFM