无法将 am/pm 的日期时间从字符转换为整数

Can't convert datetime with am/pm from character to integer

从 csv 文件上传日期时间数据后,我可以看到带有 am/pm 的日期时间,但它是字符格式,因此无法添加回归线。 当尝试使用 stprtime 转换为整数时,我创建了一个新列,它现在是一个整数,但是它丢失了 am/pm 信息。我怎样才能保留这些信息?

样本数据"wpplot":

    Date    Irrigation  Rep ID  WP
6/29/17 12:40 PM    Reduced 1   11B -14.3
6/29/17 12:50 PM    Reduced 1   11B -14.4
6/29/17 1:00 AM Reduced 1   11B -14.5
6/29/17 1:10 AM Reduced 1   11B -14.5
6/29/17 1:20 AM Reduced 1   11B -14.5
6/29/17 1:30 AM Reduced 1   11B -14.5
6/29/17 1:40 AM Reduced 1   11B -14.5
6/29/17 1:50 AM Reduced 1   11B -14.5
6/29/17 2:00 AM Reduced 1   11B -14.5
6/29/17 2:10 AM Reduced 1   11B -14.5
6/29/17 2:20 AM Reduced 1   11B -14.5
6/29/17 2:30 AM Reduced 1   11B -14.5

代码:

attach(wpplot)
wpplot$datefinish<-strptime(wpplot$Date, format = "%m/%d/%y %H:%M %p")

更新:

在使用 strptime 时,我无法区分 am/pm。语言环境设置为 English_United 个州(OS 是 Windows)。

> Sys.getlocale("LC_TIME") 
[1] "English_United States.1252"
> 
> Sys.setlocale("LC_TIME", "English")
[1] "English_United States.1252" 
wpplot$datefinish<-strptime(wpplot$Date, format = "%m/%d/%y %I:%M %p")
> datefinish
[1] "2017-06-29 12:40:00 PDT" "2017-06-29 12:50:00 PDT" 
"2017-06-29 01:00:00 PDT" "2017-06-29 01:10:00 PDT"

am/pm 格式仅在以小写形式编写时才有效,而不是像您的示例中的 AM/PM 格式。另请注意,我将 %H 更改为 %I,如 ?strptime 中所示。

以下对我有用。

wpplot$Date       <- tolower(wpplot$Date)
wpplot$datefinish <- strptime(wpplot$Date, format = "%m/%d/%y %I:%M %p")

然而,在文档中,它还指出 AM/PM 行为是特定于语言环境的:

Locale-specific conversions to and from character strings are used where appropriate and available. This affects the names of the days and months, the AM/PM indicator (if used) and the separators in formats such as %x and %X, via the setting of the LC_TIME locale category.

更新

我们可以稍微更改一下时间,以确保我们正确理解 am/pm 概念(12:40 AM 是下午还是刚过午夜?)。

wpplot$Date[1] <- "6/29/17 02:40 pm"  # This is definitely 14:40 29th of June

# CORRECT:
strptime(wpplot$Date, format = "%m/%d/%y %I:%M %p")
# [1] "2017-06-29 14:40:00 CEST" "2017-06-29 12:50:00 CEST"
# [3] "2017-06-29 01:00:00 CEST" "2017-06-29 01:10:00 CEST"
# [5] "2017-06-29 01:20:00 CEST"

请注意,我使用的是 format = "%m/%d/%y %I:%M %p" 而不是 format = "%m/%d/%y %H:%M %p":

# WRONG
strptime(wpplot$Date, format = "%m/%d/%y %H:%M %p")
# [1] "2017-06-29 02:40:00 CEST" "2017-06-29 12:50:00 CEST"
# [3] "2017-06-29 01:00:00 CEST" "2017-06-29 01:10:00 CEST"
# [5] "2017-06-29 01:20:00 CEST"