首页 > 解决方案 > 为什么 R 的 strftime 会返回上个月的午夜?

问题描述

这正好在边缘,是一个病态的案例,但它给我带来了麻烦:

> strftime(as.POSIXct('2016-07-01', tz = 'UTC'), '%m')
[1] "06"

好像应该是 7 点,虽然我知道现在是午夜。这些是7:

> strftime(as.POSIXct('2016-07-02', tz = 'UTC'), '%m')
[1] "07"
> strftime(as.POSIXct('2016-07-01'), '%m')
[1] "07"

这里发生了什么?

标签: rdatetimestrftime

解决方案


将时区添加到strftime

strftime(as.POSIXct('2016-07-01', tz = 'UTC'), '%m', tz="UTC")
[1] "07"

解释:

您只为as.POSIXct. 然后您在strftime 指定时区的情况下使用,这会导致strftime回退到其默认值

来自?strftime

tz一个字符串,指定用于转换的时区。系统特定(参见 as.POSIXlt)

如果您的系统时区不是UTC,则可能会导致这种差异。


推荐阅读