R的基础strptime
函数给出了我不期望的输出。
这可以按预期工作:
strptime(20130203235959, "%Y%m%d%H%M%S")
# yields "2013-02-03 23:59:59"
这也是:
strptime(20130202240000, "%Y%m%d%H%M%S")
# yields "2013-02-03"
......但事实并非如此。为什么?
strptime(20130203000000, "%Y%m%d%H%M%S")
# yields NA
更新
使用以下命令在Mac 10.7.5系统上生成的日志中显示值20130204000000
:
➜ ~ echo `date +"%Y%m%d%H%M%S"`
20130204000000
更新2
我甚至试过lubridate,这似乎是建议:
> parse_date_time(c(20130205000001), c("%Y%m%d%H%M%S"))
1 parsed with %Y%m%d%H%M%S
[1] "2013-02-05 00:00:01 UTC"
> parse_date_time(c(20130205000000), c("%Y%m%d%H%M%S"))
1 failed to parse.
[1] NA
...然后有趣的是,当我向now()
添加足够的秒数以达到午夜时,它打印出“00:00:00”:
> now() + new_duration(13000)
[1] "2013-02-10 00:00:00 GMT"
答案 0 :(得分:2)
我在解析日期时应该使用character
而不是numeric
:
> strptime(20130203000000, "%Y%m%d%H%M%S") # No!
[1] NA
> strptime("20130203000000", "%Y%m%d%H%M%S") # Yes!
[1] "2013-02-03"
原因似乎是我的numeric
值被转换为character
,并且我使用了太多的数字:
> as.character(201302030000)
[1] "201302030000"
> as.character(2013020300000)
[1] "2013020300000"
> as.character(20130203000000)
[1] "2.0130203e+13" # This causes the error: it doesn't fit "%Y%m%d%H%M%S"
> as.character(20130203000001)
[1] "20130203000001" # And this is why anything other than 000000 worked.
从文档中找出所需类型的快速课程:在R中,执行help(strptime)
并查看类似于下图的弹出窗口。
numeric
的原因)。
答案 1 :(得分:0)
你基本上要求的是“零”秒,这显然不存在:)
# last second of february 3rd
strptime(20130203235959, "%Y%m%d%H%M%S")
# first second of february 4rd -- notice this 'rounds up' to feb 4th
# even though it says february 3rd
strptime(20130203240000, "%Y%m%d%H%M%S")
# no such second
strptime(20130204000000, "%Y%m%d%H%M%S")
# 2nd second of february 4th
strptime(20130204000001, "%Y%m%d%H%M%S")