Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting from UTC into date format in R

Tags:

timezone

r

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!

like image 969
notrockstar Avatar asked Nov 24 '25 21:11

notrockstar


2 Answers

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')
like image 192
Justin Avatar answered Nov 27 '25 10:11

Justin


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
like image 39
Joshua Ulrich Avatar answered Nov 27 '25 12:11

Joshua Ulrich



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!