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

时间:2014-05-12 06:51:07

标签: r lubridate

鉴于POSIXct日期时间,您如何提取当月的第一天进行汇总?

library(lubridate)

full.date <- ymd_hms("2013-01-01 00:00:21")

4 个答案:

答案 0 :(得分:44)

lubridate有一个名为 select U2.Email as Subordinate, count(*) as NumLeads from USERS U2 left join LEADS l on U2.Email = l.Owner where U2.ROLE = 'PEON' and lower(v('APP_USER')) in (select EMAIL from USERS S START WITH lower(v('APP_USER')) = lower(S.SUPPER) CONNECT BY PRIOR EMAIL = SUPPER) group by U2.Email order by U2.Email 的函数,它将日期时间向下舍入。使用floor_date调用它可以完全符合您的要求:

unit = "month"

答案 1 :(得分:15)

我没有看到使用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"

答案 2 :(得分:8)

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

[1] "2013-01-01 UTC"

答案 3 :(得分:1)

我有另一个解决方案:

first.of.month <- full.date - mday(full.date) + 1

但它需要图书馆&#39; lubridate&#39;或者&#39; date.table&#39;(与data.table聚合)