【问题标题】:How to convert hours into normal dates?如何将小时转换为正常日期?
【发布时间】:2026-02-13 21:35:01
【问题描述】:

我有一些表示小时的整数,我想将它们转换为日期,然后提取年份和月份。

例如,1620936 代表 1984-12-01 00:00:00,1620960 代表 1984-12-02 00:00:00。我想知道如何在 R 中做到这一点。非常感谢。

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

【问题讨论】:

    标签: r date time


    【解决方案1】:

    时间似乎是从 1800 年 1 月 1 日开始计算的,所以试试这个:

    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)))
    

    给出这个矩阵:

         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
    

    最后一行也可以写成:

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

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

    【讨论】:

    • 非常感谢。小时数从 1800-01-01 开始计算。