可以采用“May 17, 2017”、“17/5/2017”等格式或“17-5-17 05:24:39”可以在 as.POSIXlt 中使用吗?

发布于 2025-01-09 03:57:11 字数 528 浏览 5 评论 0原文

我刚刚读到 POSIXlt 和 POSIXct 之间的区别,据说 POSIXlt 是混合文本和字符格式,如“May, 6 1985”、“1990- 9-1”或“1/20/2012”。当我尝试此类操作时,我收到错误

as.POSIXlt("May, 6 1985")
# character string is not in a standard unambiguous format

(如何)我们可以将上面引用的格式的日期提交给 POSIXlt?以下消息来源表示这种格式有效(如果我理解正确的话):12

I've just read about the difference between POSIXlt and POSIXct and it is said that POSIXlt is a mixed text and character format like "May, 6 1985", "1990-9-1" or "1/20/2012". When I try such kind of things I get an error

as.POSIXlt("May, 6 1985")
# character string is not in a standard unambiguous format

(How) can we dates with format as quoted above put forward to POSIXlt? Here are sources saying that such format works (if I get them right): 1, 2.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

记忆消瘦 2025-01-16 03:57:11

阅读 ?strptime 了解指定时间格式的所有详细信息。在本例中,您需要 %b (月份名称)、%d (月份中的某天)、%Y (4 位数字年份) 。 (这仅适用于英语区域设置,因为月份名称是特定于区域设置的。)

as.POSIXlt("May, 6 1985", format = "%b, %d %Y")

Read ?strptime for all the details of specifying a time format. In this case you want %b (for month name), %d (day of month), %Y (4-digit year). (This will only work with an English locale setting as the month names are locale-specific.)

as.POSIXlt("May, 6 1985", format = "%b, %d %Y")
奶茶白久 2025-01-16 03:57:11

如果您有甲酸盐的混合输入,您可以使用 lubridate 包中的 parse_date_time

x <- c("May, 6 1985", "1990-9-1", "1/20/2012")

y <- lubridate::parse_date_time(x, c("ymd", "mdy", "dmy"))

str(y)
# POSIXct[1:3], format: "1985-05-06" "1990-09-01" "2012-01-20"

注意c("ymd", "mdy", "dmy"),因为这决定了第一个找到的第一个转换的顺序。考虑到 6-1-2000 会遇到 mdydmy 之前有效,因此这意味着它将是六月一日而不是一月六日。

If you have mixed input of formates you can use parse_date_time from the lubridate package.

x <- c("May, 6 1985", "1990-9-1", "1/20/2012")

y <- lubridate::parse_date_time(x, c("ymd", "mdy", "dmy"))

str(y)
# POSIXct[1:3], format: "1985-05-06" "1990-09-01" "2012-01-20"

note on c("ymd", "mdy", "dmy") as this determines the order on first found first converted. Consider 6-1-2000 will encounter mdy as valid before dmy so this means it will be first of June and not sixth of January.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文