我试图将一些时间戳(字符)转换为POSIXct
对象:
> u <- "December 05, 2017 1:00 PM"
我使用as.POSIXct
如下:
> as.POSIXct(u, format = "%B %d, %Y %H:%M %p", tz = "UTC")
[1] "2017-12-05 01:00:00 UTC"
我希望输出显示小时13
而不是01
:
"2017-12-05 13:00:00 UTC"
我已经看到这里发布的问题:Parse timestamp with a.m./p.m但我似乎有正确的输入和格式字符串(%p
)。
as.POSIXct
似乎完全忽略字符串的AM / PM部分,因此AM时间戳工作正常,但PM戳记滞后12小时。以下是一些数据来说明这一点:
> sample_tstamps
[1] "December 05, 2017 8:00 AM" "December 05, 2017 9:00 AM" "December 05, 2017 10:00 AM" "December 05, 2017 11:00 AM"
[5] "December 05, 2017 12:00 PM" "December 05, 2017 1:00 PM" "December 05, 2017 2:00 PM" "December 05, 2017 3:00 PM"
[9] "December 05, 2017 4:00 PM" "December 05, 2017 5:00 PM"
> as.POSIXct(sample_tstamps, format = "%B %d, %Y %H:%M %p", tz = "UTC")
[1] "2017-12-05 08:00:00 UTC" "2017-12-05 09:00:00 UTC" "2017-12-05 10:00:00 UTC" "2017-12-05 11:00:00 UTC"
[5] "2017-12-05 12:00:00 UTC" "2017-12-05 01:00:00 UTC" "2017-12-05 02:00:00 UTC" "2017-12-05 03:00:00 UTC"
[9] "2017-12-05 04:00:00 UTC" "2017-12-05 05:00:00 UTC"
答案 0 :(得分:0)
使用R-package lubridate
:
u <- "December 05, 2017 1:00 PM"
lubridate::mdy_hm(u)
#[1] "2017-12-05 13:00:00 UTC"
答案 1 :(得分:0)
我们需要%I
而不是%H
as.POSIXct(u, format = "%B %d, %Y %I:%M %p", tz = "UTC")
#[1] "2017-12-05 13:00:00 UTC"