简体   繁体   English

使用 lubridate 在 R 中格式化日期

[英]Format date in R with lubridate

My input data, formatted as character, looks like this我的输入数据,格式化为字符,看起来像这样

"2020-07-10T00:00:00"

I tried我试过了

library(lubridate)
mdy_hms("2020-07-10T00:00:00", format='%Y-%m-%dT%H:%M:%S', tz=Sys.timezone())

But I get但我明白了

[1] NA NA Warning message: All formats failed to parse. [1] NA NA 警告消息:所有格式都无法解析。 No formats found.未找到格式。

I tried the more flexibel approach parse_date_time() , but without luck我尝试了更灵活的方法parse_date_time() ,但没有运气

parse_date_time("2020-07-10T00:00:00", '%Y-%m-%dT%H:%M:%S', tz=Sys.timezone())

How can I convert this date "2020-07-10T00:00:00" to a date R recognizes?如何将此日期“2020-07-10T00:00:00”转换为 R 识别的日期? Note: I am not interested in the time really, only the date!注意:我真的对时间不感兴趣,只对日期感兴趣!

Why not just为什么不只是

as.Date("2020-07-10T00:00:00")
# [1] "2020-07-10"

Fun fact:有趣的事实:

as.Date("2020-07-101sddT00:1sdafsdfsdf0:00sdfzsdfsdfsdf")
# [1] "2020-07-10"

Assuming that the 07 is the month of July, and the 10 is the 10th:假设 07 是 7 月,10 是 10 日:

x <- "2020-07-10T00:00:00"
ymd_hms(x, tz = Sys.timezone())

> [1] "2020-07-10 AEST"

If it's in format year-day-month, swap the ymd for ydm.如果格式为年-日-月,请将 ymd 交换为 ydm。

Hope this helps!希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM