【问题标题】:How to create new column with timestamps, using old column of date/time in 24 hour format如何使用 24 小时格式的旧日期/时间列创建带有时间戳的新列
【发布时间】:2022-01-06 19:44:12
【问题描述】:

我有一个数据框,其中有一列包含日期/时间。我已提取月份和日期以创建 2 个新列,但我正在尝试创建另一个带时间的列,现在我已将时间转换为 24 小时格式,它无法正常工作

这是我的数据框中的列的样子

# A tibble: 6 x 1
  df                 
  <dttm>             
1 2021-06-01 08:00:00
2 2021-06-01 08:15:00
3 2021-06-01 08:30:00
4 2021-06-01 08:45:00
5 2021-11-25 21:46:40
6 2021-11-25 22:01:40

这里是数据框列

df = structure(list(df = structure(c(1622552400, 1622553300, 1622554200, 
                                     1622555100, 1637894800, 1637895700), class = c("POSIXct", "POSIXt"
                                     ), tzone = "EST")), row.names = c(NA, 6L), class = "data.frame")

当我的时间是 12 小时格式时,我使用了这段代码并且它有效

  mutate(month = lubridate::month(Date_Time_GMT_3), 
         year = lubridate::year(Date_Time_GMT_3),
         day = lubridate::day(Date_Time_GMT_3),
#CODE FOR TIME COLUMN
         time = lubridate::hms(substr(Date_Time_GMT_3, 11, 
                                      nchar(Date_Time_GMT_3))))

现在我已将时间格式更改为 24 小时,但出现此错误

Warning message:
Problem with `mutate()` column `time`.
i `time = lubridate::hms(substr(Date_Time_GMT_3, 11, nchar(Date_Time_GMT_3)))`.
i Some strings failed to parse, or all strings are NAs 

知道如何解决这个问题吗?

【问题讨论】:

    标签: r datetime


    【解决方案1】:

    试试sub 而不是substr

    df %>% mutate(month = lubridate::month(df), 
             year = lubridate::year(df),
             day = lubridate::day(df),
             time = lubridate::hms(sub(".* ","",df)))
                       df month year day        time
    1 2021-06-01 08:00:00     6 2021   1    8H 0M 0S
    2 2021-06-01 08:15:00     6 2021   1   8H 15M 0S
    3 2021-06-01 08:30:00     6 2021   1   8H 30M 0S
    4 2021-06-01 08:45:00     6 2021   1   8H 45M 0S
    5 2021-11-25 21:46:40    11 2021  25 21H 46M 40S
    6 2021-11-25 22:01:40    11 2021  25  22H 1M 40S
    

    数据

    df <- structure(list(df = structure(c(1622552400, 1622553300, 1622554200, 
    1622555100, 1637894800, 1637895700), class = c("POSIXct", "POSIXt"
    ), tzone = "EST")), row.names = c(NA, 6L), class = "data.frame")
    

    【讨论】:

      猜你喜欢
      • 2016-05-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多