3

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

更新

该值20130204000000显示在我使用以下命令在 Mac 10.7.5 系统上生成的日志中:

➜  ~  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"
4

2 回答 2

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"

The reason for this seems to be that my numeric value gets cast to character, and I used one too many digits:

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

A quick lesson in figuring out the type you need from the docs: In R, execute help(strptime) and see a popup similar to the image below.

  • The red arrow points to the main argument to the function, but does not specify the type (which is why I just tried numeric).
  • The green arrow points to the type, which is in the document's title.

enter image description here

于 2013-02-09T20:41:06.473 回答
0

你本质上是在要求“zeroeth”秒,这显然不存在:)

# 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")
于 2013-02-07T00:05:16.663 回答