【问题标题】:datetime object to minutes: I need 3 packages日期时间对象到分钟:我需要 3 个包
【发布时间】:2021-11-08 00:05:08
【问题描述】:

我想知道我是否遗漏了什么?!

我想知道:有没有更好/更短的方法从日期时间对象中获取分钟数:

目前学习的课程:

Extract time (HMS) from lubridate date time object?

converting from hms to hour:minute in r, or rounding in minutes from hms

R: Convert hours:minutes:seconds

我的小标题:

df <- structure(list(dttm = structure(c(-2209068000, -2209069200, -2209061520, 
-2209064100, -2209065240), tzone = "UTC", class = c("POSIXct", 
"POSIXt"))), row.names = c(NA, -5L), class = c("tbl_df", "tbl", 
"data.frame"))

# A tibble: 5 x 1
  dttm               
  <dttm>             
1 1899-12-31 02:00:00
2 1899-12-31 01:40:00
3 1899-12-31 03:48:00
4 1899-12-31 03:05:00
5 1899-12-31 02:46:00

我想添加一个以分钟为整数的新列:

到目前为止我的方法:

library(dplyr)
library(lubridate)  # ymd_hms
library(hms)        # as_hms
library(chron)      # times

test %>% 
    mutate(dttm_min = as_hms(ymd_hms(dttm)),
           dttm_min = 60*24*as.numeric(times(dttm_min)))

# A tibble: 5 x 2
  dttm                dttm_min
  <dttm>                 <dbl>
1 1899-12-31 02:00:00      120
2 1899-12-31 01:40:00      100
3 1899-12-31 03:48:00      228
4 1899-12-31 03:05:00      185
5 1899-12-31 02:46:00      166

这给了我想要的结果,但我需要 3 个包。有没有更直接的方法?

【问题讨论】:

  • 这是一个很好的答案。因此,我链接了这个答案。就我个人而言,我真的很难在我的大脑中获得as.POSIXlt。至少在这个阶段。所以我想问问其他方法。我希望这没问题!

标签: r datetime time lubridate chron


【解决方案1】:

这是一个基本的 R 方式 -

您可以使用format 提取时间,将日期更改为'1970-01-01'(因为R 日期时间以'1970-01-01' 开头),转换为数字并将时间除以60 以获得以分钟为单位的持续时间。

as.numeric(as.POSIXct(paste('1970-01-01', format(df$dttm, '%T')), tz = 'UTC'))/60
#[1] 120 100 228 185 166

【讨论】:

  • 这是一个很好的答案,让我的知识更进一步!我决定接受 Rui Barradas 的回答,因为这更符合我的实际需求!
【解决方案2】:

这里有两种方法。

基础 R

with(df, as.integer(format(dttm, "%M")) + 60*as.integer(format(dttm, "%H")))
#[1] 120 100 228 185 166

另一个基本 R 选项,使用建议的 here"POSIXlt"

minute_of_day <- function(x){
  y <- as.POSIXlt(x)
  60*y$hour + y$min
}

minute_of_day(df$dttm)
#[1] 120 100 228 185 166

lubridate

lubridate::minute(df$dttm) + 60*lubridate::hour(df$dttm)
#[1] 120 100 228 185 166

如果加载了包,这可以简化为,输出相同,

library(lubridate)
minute(df$dttm) + 60*hour(df$dttm)

【讨论】:

  • 这是最适合我现阶段需求的方法。谢谢!
【解决方案3】:

我们可以使用

library(data.table)
 as.numeric(as.ITime(format(df$dttm, '%T')))/60
[1] 120 100 228 185 166

【讨论】:

    【解决方案4】:

    为了完整起见,一天中的时间(以分钟为单位)可以通过在 POSIXct 日期时间对象和一天的开始之间取 difftime() 来计算,例如,

    difftime(df$dttm, lubridate::floor_date(df$dttm, "day"), units = "min")
    
    Time differences in mins
    [1] 120 100 228 185 166
    

    除了基本 R 之外,只需要一个其他包。

    根据help("difftime")difftime() 返回一个“difftime”类的对象,其属性指示单位。

    【讨论】:

      猜你喜欢
      • 2013-10-27
      • 2011-07-29
      • 2021-11-29
      • 1970-01-01
      • 1970-01-01
      • 2011-03-28
      • 1970-01-01
      • 1970-01-01
      • 2020-11-29
      相关资源
      最近更新 更多