问题
I have a UTC timestamp. I want to convert it into YYYY/MM/DD format in R.
For example, 1318394558766. I tried format command unsuccessfully.
Any help is appreciated.
Thanks!
回答1:
You can use as.POSIXct or as.POSIXlt. However you have to know the origin date from which your number of milliseconds started.
as.POSIXct(1318394558766/1000, origin='1970-01-01')
> unlist(as.POSIXlt(1318394558766/1000, origin='1970-01-01'))
sec min hour mday mon year wday yday isdst
38.766 42.000 21.000 11.000 9.000 111.000 2.000 283.000 1.000
>
Then you can use format to get the desired YYYY/MM/DD:
format(as.POSIXct(1318394558766/1000, origin='1970-01-01'), format='%Y/%m/%d')
回答2:
In addition to Justin's answer (and because I can't make comments) you may want to add the tz to the transformation.
as.POSIXct(1318394558766/1000, origin='1970-01-01')
[1] "2011-10-12 05:42:38 EST"
as.POSIXct(1318394558766/1000, origin='1970-01-01', tz="UTC")
[1] "2011-10-12 04:42:38 UTC"
For more information see;
?timezone
回答3:
Yet another solution is to use .POSIXct:
utc <- .POSIXct(1318394558766/1000, tz="UTC")
Then you can easily convert utc to a Date or character vector:
as.Date(utc) # Date vector
format(utc, "%Y-%m-d") # character vector
来源:https://stackoverflow.com/questions/11233960/converting-from-utc-into-date-format-in-r