【问题标题】:convert datetime to three letter month and year in R [duplicate]在R中将日期时间转换为三个字母的月份和年份[重复]
【发布时间】:2021-03-23 01:01:06
【问题描述】:

我需要帮助将日期时间的第一列转换为 3 个字母的月份和年份。

DF

Datetime              ID      Name
2020-01-01 10:12:14   I-1     Rnad
2020-01-01 16:32:43   I-2     Rnxa

需要的输出

Datetime              ID      Name   Month
2020-01-01 10:12:14   I-1     Rnad   Jan-20
2020-01-01 16:32:43   I-2     Rnxa   Jan-20

【问题讨论】:

    标签: r date


    【解决方案1】:

    试试这个索菲亚:

    #Code
    df$Month <- format(as.POSIXct(df$Datetime,format='%Y-%m-%d %H:%M:%S',
                                  tz = 'GMT'),"%b-%y")
    

    输出:

    df
                 Datetime  ID Name  Month
    1 2020-01-01 10:12:14 I-1 Rnad Jan-20
    2 2020-01-01 16:32:43 I-2 Rnxa Jan-20
    

    使用的一些数据:

    #Data
    df <- structure(list(Datetime = c("2020-01-01 10:12:14", "2020-01-01 16:32:43"
    ), ID = c("I-1", "I-2"), Name = c("Rnad", "Rnxa")), row.names = c(NA, 
    -2L), class = "data.frame")
    

    【讨论】:

      【解决方案2】:

      您可以将format 函数与strptime 缩写一起使用。

      my_df$Month <- format(my_df$Datetime, format = "%b-%y"
      

      【讨论】:

        猜你喜欢
        • 2014-12-29
        • 2021-12-18
        • 2017-01-27
        • 1970-01-01
        • 2018-12-24
        • 2014-03-25
        • 1970-01-01
        • 2021-09-26
        • 2021-11-04
        相关资源
        最近更新 更多