0

I have the following date which I want to convert into POSIX time. I followed this answer but there's a difference between the input and the output date if I convert the date back.

char_date <- "2012-04-27T20:48:14"
unix_date <- as.integer(as.POSIXct(char_date, origin="1970-01-01"))
unix_date
# [1] 1335448800

which translates back to Thu, 26 Apr 2012 14:00:00.

What am I messing up?

Community
  • 1
  • 1
CptNemo
  • 6,455
  • 16
  • 58
  • 107

2 Answers2

2

No need for sub and you should always define the time zone:

x <- as.POSIXct("2012-04-27T20:48:14", format="%Y-%m-%dT%H:%M:%S", tz="CET")
#[1] "2012-04-27 20:48:14 CEST"
as.numeric(x)
#[1] 1335552494
Roland
  • 127,288
  • 10
  • 191
  • 288
0

I think there are 2 issue in play here: The T character is affecting the character parser so it ingores the time part, and I assume your timezone is UTC+10, which is why your translation is at 2pm the previous day.

(as.POSIXct(char_date, origin="1970-01-01"))
[1] "2012-04-27 BST"

(as.POSIXct(sub("T"," ",char_date), origin="1970-01-01"))
[1] "2012-04-27 20:48:14 BST"
James
  • 65,548
  • 14
  • 155
  • 193
  • Should I indicate the time where the timestamp was taken or mine? `(as.POSIXct(sub("T"," ",char_date), origin="1970-01-01", tz="CET"))`? – CptNemo Feb 06 '14 at 10:37
  • @CptNemo Depends on what you think, but if you dont give one, it will assume the local timezone of your machine, so you will need to be consistent. – James Feb 06 '14 at 10:54