How to Convert Millisecond to Date in R

Master R

By Guangming Lang Comment

Sometimes, we receive data where the timestamps are milliseconds and we want to convert them to dates. This is quite easy in R. We just need to use the as.POSIXct() function. Here’s a function wrapper I wrote to make it even easier.

ms.to.date = function(x, t0="1970-01-01", timezone) {
        ## @x: a numeric vector
        ## @t0: a string of the format "yyyy-mm-dd", specifying the date that
        ##      corresponds to 0 millisecond
        ## @timezone: a string specifying a timezone that can be recognized by R
        ## return: a POSIXct vector representing calendar dates and times        
        as.POSIXct(x, origin=t0, tz=timezone)
}

Here’s an example of how to use it:

date.in.ms = c(1348034028, 1348034031)
ms.to.date(date.in.ms, timezone="America/Los_Angeles")
## [1] "2012-09-18 22:53:48 PDT" "2012-09-18 22:53:51 PDT"

If you enjoyed this post, get updates. It's FREE