Converting from UTC into date format in R

2019-07-31 06:17发布

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!

标签: r timezone
3条回答
smile是对你的礼貌
2楼-- · 2019-07-31 06:22

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
查看更多
Evening l夕情丶
3楼-- · 2019-07-31 06:36

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
查看更多
女痞
4楼-- · 2019-07-31 06:49

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')
查看更多
登录 后发表回答