Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to elegantly convert datetime from decimal to "%d.%m.%y %H:%M:%S"?

Tags:

date

split

r

I am doing an experiment which produces automatically logged data. The software produces a timestamp that is of the format 41149.014850. I would like to convert this decimal timestamp to 28.08.2012 00:21:23. How can I do this in R most elegantly?

I tried using the function strsplit and also the function as.Date with a specified origin, and also the times function. But to no avail. I have problems in splitting the timestamp into two numbers that I can access with the functions as.Date and times.

Here is some demo code:

myDatetime <- c(41149.004641, # 28.08.2012  00:06:41
41149.009745, # 28.08.2012  00:14:02
41149.014850, # 28.08.2012  00:21:23
41149.019954) # 28.08.2012  00:28:44

## not working out for me
Dat.char <- as.character(myDatetime)
date.split <- strsplit(Dat.char, split = "\\.")
## how to proceed from here, if it is a good way at all
like image 352
Strohmi Avatar asked Aug 28 '12 14:08

Strohmi


2 Answers

You dates are in an Excel-like date format (days after January 1, 1900), so you need to convert them to an R date format. Then you can convert it to a datetime format (POSIXct).

# first convert to R Date
datetime <- as.Date(myDatetime-1, origin="1899-12-31")
# now convert to POSIXct
(posixct <- .POSIXct(unclass(datetime)*86400, tz="GMT"))
# [1] "2012-08-28 00:06:40 GMT" "2012-08-28 00:14:01 GMT"
# [3] "2012-08-28 00:21:23 GMT" "2012-08-28 00:28:44 GMT"
# times are sometimes off by 1 second, add more digits to seconds to see why
options(digits.secs=6)
posixct
# [1] "2012-08-28 00:06:40.9823 GMT" "2012-08-28 00:14:01.9680 GMT"
# [3] "2012-08-28 00:21:23.0399 GMT" "2012-08-28 00:28:44.0256 GMT"
# round to nearest second
(posixct <- round(posixct, "sec"))
# [1] "2012-08-28 00:06:41 GMT" "2012-08-28 00:14:02 GMT"
# [3] "2012-08-28 00:21:23 GMT" "2012-08-28 00:28:44 GMT"
# now you can convert to your desired format
format(posixct, "%d.%m.%Y %H:%M:%S")
# [1] "28.08.2012 00:06:41" "28.08.2012 00:14:02"
# [3] "28.08.2012 00:21:23" "28.08.2012 00:28:44"
like image 185
Joshua Ulrich Avatar answered Sep 23 '22 03:09

Joshua Ulrich


This gets close: The numbers indicate the number of seconds since a date close to 1/1/1900:

as.POSIXct(x*3600*24, origin=as.Date("1900-01-01")-2, tz="UTC")
[1] "2012-08-28 01:06:40 BST" "2012-08-28 01:14:01 BST" "2012-08-28 01:21:23 BST"
[4] "2012-08-28 01:28:44 BST"

There still is a timezone offset in there.

like image 44
Andrie Avatar answered Sep 22 '22 03:09

Andrie