【问题标题】:Changing the format of date with month in letters用字母更改月份的日期格式
【发布时间】:2018-01-13 01:41:12
【问题描述】:

我有日期和时间列。主要问题是 csv 文件中的年份(2016 年)不完整,OCT 不是数字。

Date        Time         rtime
20-Oct-16 14:02:00       20-Oct-16 14:02:00
20-Oct-16 14:02:03       20-Oct-16 14:02:03

我想要另一个名为 newtime 的列,采用这种格式

newtime
2016-10-20 14:02:00
2016-10-20 14:02:03 

关于如何以常规数字格式制作月份并将 16 变成 2016 年的任何建议。

【问题讨论】:

  • 使用 dmy_hms(df$rtime) 例如dmy_hms("20-Oct-16 14:02:00")

标签: r date time format


【解决方案1】:

使用 lubridate,您无需指定月份是带有名称 (Oct) 还是十进制数 (10) 或年份是 2016 年还是 16 年。Lubridate 函数解析异构日期时间格式。例如:

library(lubridate)
df$newtime = dmy_hms(df$rtime) 

       Date     Time              rtime             newtime
1 20-Oct-16 14:02:00 20-Oct-16 14:02:00 2016-10-20 14:02:00
2 20-Oct-16 14:02:03 20-Oct-16 14:02:03 2016-10-20 14:02:03

如果您使用strptime,那么您需要定义格式。请参见 ?strptime。

【讨论】:

    【解决方案2】:

    我们可以使用strptime

    strptime("20-Oct-16 14:02:00", "%d-%b-%y %H:%M:%S")
    

    dmy_hms 来自lubridate

    lubridate::dmy_hms("20-Oct-16 14:02:00")
    

    【讨论】:

      【解决方案3】:

      我们也可以使用as.POSIXctformat

      as.POSIXct("20-Oct-16 14:02:00", format = "%d-%b-%y %H:%M:%S")
      #[1] "2016-10-20 14:02:00 IST"
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-10-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-10-19
        • 2020-10-18
        • 1970-01-01
        相关资源
        最近更新 更多