Yang Yang
Yang Yang

Reputation: 902

How to convert hours into normal dates?

I have some integers which represent hours and I want to convert them into dates and then extract the year and month.

For example, 1620936 stands for 1984-12-01 00:00:00 and 1620960 stands for 1984-12-02 00:00:00. I wonder how I can do this in R. Thanks a lot.

Time = c(1620936,1620960,1620984,1621008,1621032,1621056,1621080,1621104)

Upvotes: 0

Views: 71

Answers (1)

G. Grothendieck
G. Grothendieck

Reputation: 269885

it seems that the hours are measured from Jan 1, 1800 so try this:

toDate <- function(x) as.Date("1800-01-01") + x / 24

dat <- toDate(Time)
sapply(c(year="%Y", month="%m", day="%d"), function(fmt) as.numeric(format(dat, fmt)))

giving this matrix:

     year month dayt
[1,] 1984    12    1
[2,] 1984    12    2
[3,] 1984    12    3
[4,] 1984    12    4
[5,] 1984    12    5
[6,] 1984    12    6
[7,] 1984    12    7
[8,] 1984    12    8

The last line could alternately be written as:

with(unclass(as.POSIXlt(dat)), cbind(year = year+1900, month = mon+1, day = mday))

or

library(chron)

do.call("cbind", month.day.year(dat))

Upvotes: 2

Related Questions