使用lubridate从POSIXct日期时间开始的月份的第一天

nac*_*dus 19 r lubridate

给定POSIXct日期时间,如何提取当月的第一天进行聚合?

library(lubridate)

full.date <- ymd_hms("2013-01-01 00:00:21")
Run Code Online (Sandbox Code Playgroud)

Fra*_*ank 49

lubridate有一个函数floor_date,它将日期时间向下舍入.调用它unit = "month"完全符合您的要求:

library(lubridate)
full.date <- ymd_hms("2013-01-01 00:00:21")
floor_date(full.date, "month")

[1] "2013-01-01 UTC"
Run Code Online (Sandbox Code Playgroud)


Rol*_*and 16

我没有看到使用lubridate的理由:

full.date <- as.POSIXct("2013-01-11 00:00:21", tz="GMT")

monthStart <- function(x) {
  x <- as.POSIXlt(x)
  x$mday <- 1
  as.Date(x)
}

monthStart(full.date)
#[1] "2013-01-01"
Run Code Online (Sandbox Code Playgroud)

  • +1 表示不使用字符串格式化技巧(像我一样)。 (2认同)

nac*_*dus 9

first.of.month <- ymd(format(full.date, "%Y-%m-01"))
first.of.month

[1] "2013-01-01 UTC"
Run Code Online (Sandbox Code Playgroud)