gpt4 book ai didi

r - 为什么R包lubridate无法解析多种格式的向量?

转载 作者:行者123 更新时间:2023-12-02 02:55:18 27 4
gpt4 key购买 nike

我正在使用包lubridate来解析异构格式日期的向量并将它们转换为字符串,如下所示:

parse_date_time(c('12/17/1996 04:00:00 PM','4/18/1950 0130'), c('%m/%d/%Y %I:%M:%S %p','%m/%d/%Y %H%M'))

这是结果:

[1] NA NA
Warning message:
All formats failed to parse. No formats found.

如果我删除第一个格式字符串中的 %p ,它会错误地解析第一个日期字符串,并且仍然不会解析第二个日期字符串,如下所示:

[1] "1996-12-17 04:00:00 UTC" NA                       
Warning message:
1 failed to parse.

字符串中的 4PM 时间被解析为结果中的 4AM。

有人经历过这种奇怪的行为吗?

最佳答案

这可能与您的系统区域设置有关。

  • parse_date_time {lubridate}

    p : AM/PM indicator in the locale. Used in conjunction with I and not with H. An empty string in some locales.

因为不同的语言有不同的 AM/PM 字符串,如果您的区域设置不是英语,即使您指定,lubridate 也不会选取 AM/PM 指示符.

操作系统中的区域设置可以包括显示语言、时间格式、时区。我使用的是带有美国时区和中文语言环境的英文窗口,因此我也在时间解析中与 AM/PM 作斗争。

Sys.getlocale("LC_TIME")
[1] "Chinese (Simplified)_China.936"

您可以在 parse_date_time {lubridate} 中指定区域设置,但一开始它对我不起作用:

Sys.setlocale("LC_TIME", "en_US") 
[1] ""
Warning message:
In Sys.setlocale("LC_TIME", "en_US") :
OS reports request to set locale to "en_US" cannot be honored
  • 语言环境 {base}

    The locale describes aspects of the internationalization of a program. Initially most aspects of the locale of R are set to "C" (which is the default for the C language and reflects North-American usage). strptime for uses of category = "LC_TIME".

然后我发现this利用这一点取得了成功:

Sys.setlocale("LC_TIME", "C")
[1] "C"

在此之后解析工作:

parse_date_time('12/17/1996 04:00:00 PM', '%m/%d/%Y %I:%M:%S %p')
[1] "1996-12-17 16:00:00 UTC"

您还可以指定时区和区域设置

parse_date_time('12/17/1996 04:00:00 PM', '%m/%d/%Y %I:%M:%S %p', tz = "America/New_York", locale = "C")
[1] "1996-12-17 16:00:00 EST"

关于r - 为什么R包lubridate无法解析多种格式的向量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30338735/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com