How to convert a character date into POSIX time without loss in precision

StackOverflow https://stackoverflow.com/questions/21599949

  •  07-10-2022
  •  | 
  •  

سؤال

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?

هل كانت مفيدة؟

المحلول

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

نصائح أخرى

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"
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top