【问题标题】:R: Why does strptime always return NA when I try to format a date string?R:为什么当我尝试格式化日期字符串时,strptime 总是返回 NA?
【发布时间】:2011-07-13 20:14:17
【问题描述】:

这是我的一些数据,从文件名 AttReport_all 中读取:

Registration.Date                 Join.Time                Leave.Time
1 Jul 05, 2011 09:30 PM EDT Jul 07, 2011 01:05 PM EDT Jul 07, 2011 01:53 PM EDT
2 Jul 05, 2011 10:20 AM EDT Jul 07, 2011 01:04 PM EDT Jul 07, 2011 01:53 PM EDT
3 Jul 04, 2011 02:41 PM EDT Jul 07, 2011 12:49 PM EDT Jul 07, 2011 01:53 PM EDT
4 Jul 04, 2011 11:38 PM EDT Jul 07, 2011 12:49 PM EDT Jul 07, 2011 01:54 PM EDT
5 Jul 05, 2011 11:41 AM EDT Jul 07, 2011 12:54 PM EDT Jul 07, 2011 01:54 PM EDT
6 Jul 07, 2011 11:08 AM EDT Jul 07, 2011 01:16 PM EDT Jul 07, 2011 01:53 PM EDT

如果我这样做strptime(AttReport_all$Registration.Date, "%b %m, %Y %H:%M %p", tz=""),我会得到一个我期待日期的 NA 数组。

Sys.setlocale("LC_TIME", "C") 返回“C”

typeof(AttReport_all$Registration.Date) 返回“整数”

is.factor(AttReport_all$Registration.Date) 返回 TRUE。

我错过了什么?

这是版本输出,如果有帮助的话: 平台 i386-pc-mingw32
拱 i386
操作系统 mingw32
系统 i386、mingw32
状态
专业2
未成年人 13.0
2011 年
04月
第 13 天
svn 版本 55427
语言 R
version.string R 版本 2.13.0 (2011-04-13)

【问题讨论】:

    标签: r date


    【解决方案1】:

    strptime 自动在第一个参数上运行as.character(因此它是一个因素并不重要)并且format= 中未指定的任何尾随字符都将被忽略(因此“EDT”无关紧要)。

    唯一的问题是@Ben Bolker 确定的错字(%m 应该是%d)和%H 应该是%I?strptime 说你应该使用@987654329 @ 和 %p)。

    # %b and %m are both *month* formats
    strptime("Jul 05, 2011 09:30 PM EDT", "%b %m, %Y %H:%M %p", tz="")
    # [1] NA
    
    # change %m to %d and we no longer get NA, but the time is wrong (AM, not PM)
    strptime("Jul 05, 2011 09:30 PM EDT", "%b %d, %Y %H:%M %p", tz="")
    # [1] "2011-07-05 09:30:00"
    
    # use %I (not %H) with %p
    strptime("Jul 05, 2011 09:30 PM EDT", "%b %d, %Y %I:%M %p", tz="")
    # [1] "2011-07-05 21:30:00"
    

    【讨论】:

    • dstr
    • 似乎我的错误是 %m/%H 替换。谢谢。
    • 本应使用%d 时使用%m 导致NA。将%H%p 一起使用会导致更细微的错误。
    猜你喜欢
    • 1970-01-01
    • 2018-06-29
    • 1970-01-01
    • 2019-02-26
    • 2016-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多