【问题标题】:Converting Lubridate Period Class Time to Time Stamp Format in R将 Lubridate Period 类时间转换为 R 中的时间戳格式
【发布时间】:2021-04-05 16:25:53
【问题描述】:

我的代码读入一个 .txt 文件,该文件在一列中包含一系列时间戳。我需要为该列考虑夏令时,所以我使用 lubridate 包从这些时间戳中减去一个小时。我正在努力将周期类从 lubridate 转换回 %I:%M%:S %p 的时间格式。

这是我的代码。

  # Changing from 24 Hr to 12 Hr Format #
  raw_data_sample$Time <- format(strptime(raw_data_sample$Time, format='%H:%M:%S'), '%I:%M:%S %p')
  
  # Subtracting an Hour for Daylight Savings
  raw_data_sample$Time <- hms(raw_data_sample$Time)
  raw_data_sample$Time <- raw_data_sample$Time - hours(1)

这是我当前的输出。

c("1H 41M 54S", "1H 42M 4S", "1H 42M 14S", "1H 42M 31S", "1H 42M 41S", "1H 43M 1S")

我希望得到类似的输出

1:41:54 PM, 1:42:40 PM

有什么建议吗?谢谢!

【问题讨论】:

    标签: r time format


    【解决方案1】:

    如果我们需要减去一个小时,请在原始日期时间对象上执行此操作,然后执行formatting

    library(lubridate)
    # // convert to Datetime class 
    raw_data_sample$Time <- as.POSIXct(raw_data_sample$Time, format = "%H:%M:%S")
     # // subtract 1 hour from the Datetime and use format to change the format
    format(raw_data_sample$Time %m-% hours(1), "%I:%M:%S %p")
    

    【讨论】:

    • 感谢您的回复!我应该澄清一下,我原来的数据帧时间格式只是 HH:MM:SS,没有日期。当我写你的建议时,我得到“as.POSIXlt.character(x, tz, ...) 中的错误:字符串不是标准的明确格式”,我假设这是由于缺少日期在格式中。
    • @user14880462 只需在as.POSIXct 中指定formatformat = "%H:%M:%S"
    • 哦,非常感谢!这解决了我的问题。
    【解决方案2】:

    您可以使用parse_date_time 函数将您的周期对象转换为POSIXct,然后使用format 获得适合您的格式。

    library(lubridate)
    raw_data_sample$Time1 <- format(parse_date_time(raw_data_sample$Time, 'HMS'), '%I:%M:%S %p')
    

    例如,

    x <- period(c("1H 41M 54S", "1H 42M 4S", "1H 42M 14S", "1H 42M 31S", "1H 42M 41S", "1H 43M 1S"))
    format(parse_date_time(x, 'HMS'), '%I:%M:%S %p')
    #[1] "01:41:54 AM" "01:42:04 AM" "01:42:14 AM" "01:42:31 AM" "01:42:41 AM" "01:43:01 AM"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-09-08
      • 1970-01-01
      • 1970-01-01
      • 2021-06-15
      • 2016-11-26
      • 2011-09-18
      • 1970-01-01
      相关资源
      最近更新 更多