【问题标题】:NA for 1 particular date when converting dates from "character" format to "POSIXct" with as.POSIXct使用 as.POSIXct 将日期从“字符”格式转换为“POSIXct”时 1 个特定日期的 NA
【发布时间】:2020-02-27 18:11:46
【问题描述】:

我正在使用 as.POSIXct() 将字符串向量转换为日期格式。 奇怪的是:

as.POSIXct("2017-03-26 03:00:00.000",format="%Y-%m-%d %H")

#Gives

"2017-03-26 03:00:00 CEST"

#While

as.POSIXct("2017-03-26 02:00:00.000",format="%Y-%m-%d %H")

#Outputs
NA

这真是令人困惑和沮丧。看起来该功能确实不喜欢特定时间: 02:00:00.000

【问题讨论】:

    标签: r posixct


    【解决方案1】:

    我们可以指定%T 作为时间。在格式中,有分、秒和毫秒。所以,%H 只匹配小时部分

    as.POSIXct("2017-03-26 02:00:00.000",format="%Y-%m-%d %T")
    [1] "2017-03-26 02:00:00 EDT"
    

    或者也要注意毫秒

    as.POSIXct("2017-03-26 02:00:00.000",format="%Y-%m-%d %H:%M:%OS")
    #[1] "2017-03-26 02:00:00 EDT"
    

    或使用lubridate

    library(lubridate)
    ymd_hms("2017-03-26 02:00:00.000")
    

    【讨论】:

    • 您的代码 sn-ps 仍然为我输出 NA。这是否与您的输出中有“EDT”有关,而我有“CEST”?
    • @Niltzable 你能指定tz = "CEST"
    • @Niltzable 尝试使用 lubridate library(lubridate);ymd_hms("2017-03-26 02:00:00.000")
    • 使用 lubridate 它可以工作并输出:“2017-03-26 02:00:00 UTC”。这可能是“CEST”的一些问题。非常感谢!
    • @Niltzable 与那个时区,我收到警告,但如果我这样做as.POSIXct("2017-03-26 02:00:00.000",format="%Y-%m-%d %H:%M%OS", tz = "Europe/Berlin")# [1] NA。可能是那个时候的语言环境问题,特别是当有夏令时和所有
    【解决方案2】:

    这是一个夏令时问题,时间:

    "2017-03-26 02:00:00.000" 在瑞典不存在,因为我们在这个日期更改为“夏令时”时损失了一个小时。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-30
      • 1970-01-01
      相关资源
      最近更新 更多