r - 在 lubridate 中,有没有办法将 ymd_hms() 日期格式转换为数字格式,然后再转换回来?

标签 r data.table

目前,我将日期数据存储在大型 data.table 表的列中。日期数据类似于:

dt1 <- data.table(Person = seq(6), Date = ymd_hms(c("2007-1-1 12:31:25 PST", "2007-1-3 09:31:25 PST", "2007-1-9 15:31:22 PST", "2007-1-17 21:41:23 PST", "2007-1-30 02:04:22 PST", "2007-2-2 02:07:12 PST")))

> dt1
Person                Date
1:      1 2007-01-01 12:31:25
2:      2 2007-01-03 09:31:25
3:      3 2007-01-09 15:31:22
4:      4 2007-01-17 21:41:23
5:      5 2007-01-30 02:04:22
6:      6 2007-02-02 02:07:12

ymd_hms() 是 lubridate 包中的一个函数。现在,当我将日期转换为数字时,我得到:

dt1[,Date:=as.numeric(Date)]

> dt1
Person       Date
1:      1 1167654685
2:      2 1167816685
3:      3 1168356682
4:      4 1169070083
5:      5 1170122662
6:      6 1170382032

此后,我尝试了各种方法,但无法将日期转换回原始格式。有人知道一个简单的功能吗?谢谢!

最佳答案

我查看了 ?lubridate,但没有看到任何关于支持将数字转换为 POSIXct 的提及。

因此,我认为您“必须”使用基础 R 来完成它。

Date = ymd_hms(c("2007-1-1 12:31:25 PST", "2007-1-3 09:31:25 PST", 
                 "2007-1-9 15:31:22 PST", "2007-1-17 21:41:23 PST", 
                 "2007-1-30 02:04:22 PST", "2007-2-2 02:07:12 PST"))
as.numeric(Date)
#[1] 1167654685 1167816685 1168356682 1169070083 1170122662 1170382032
as.POSIXct(as.numeric(Date), origin="1970-01-01", tz="UTC")
#[1] "2007-01-01 12:31:25 UTC" "2007-01-03 09:31:25 UTC"
#[3] "2007-01-09 15:31:22 UTC" "2007-01-17 21:41:23 UTC"
#[5] "2007-01-30 02:04:22 UTC" "2007-02-02 02:07:12 UTC"

附带说明一下,您的时间是在 UTC 中创建的,而不是“PST”。如果这不是您想要的,也许您打算在 ymd_hms() 调用中包含 tz=America/Los_Angeles

Date <- ymd_hms(c("2007-1-1 12:31:25 PST", "2007-1-3 09:31:25 PST", 
                  "2007-1-9 15:31:22 PST", "2007-1-17 21:41:23 PST", 
                  "2007-1-30 02:04:22 PST", "2007-2-2 02:07:12 PST"),
                tz="America/Los_Angeles")

#Sys.setenv(TZ="America/Los_Angeles") 
as.POSIXct(as.numeric(Date), origin="1970-01-01")
#[1] "2007-01-01 12:31:25 PST" "2007-01-03 09:31:25 PST"
#[3] "2007-01-09 15:31:22 PST" "2007-01-17 21:41:23 PST"
#[5] "2007-01-30 02:04:22 PST" "2007-02-02 02:07:12 PST"

关于r - 在 lubridate 中,有没有办法将 ymd_hms() 日期格式转换为数字格式,然后再转换回来?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26068963/

相关文章:

r - 使用 R expss 和 data.table 是否可以从 csv 文件加载 data.table 标签,而不是手动输入代码?

r - 将数组与 R 中的 data.table 相乘

r - 一个 ggplot2 图中的 PCA 图和方差比例表 - R

r - 在 plotly 中从 x+y+z=6 方程绘制 3d 平面

反向评分向量

r - 使用 data.table 按与另一行的距离选择行

在 data.table 中按组进行回归和汇总统计

r - 何时以及为什么 "print"需要两次尝试打印 "data.table"?

R 并润滑 : do the intervals in x fit into any of the intervals in y?

r - 并行和 Rcpp Armadillo 问题 : Possible variable corruption between cluster workers