33

Given a POSIXct date time, how do you extract the first day of the month for aggregation?

library(lubridate)

full.date <- ymd_hms("2013-01-01 00:00:21")
nacnudus
  • 6,328
  • 5
  • 33
  • 47

5 Answers5

74

lubridate has a function called floor_date which rounds date-times down. Calling it with unit = "month" does exactly what you want:

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

[1] "2013-01-01 UTC"
Sirko
  • 72,589
  • 19
  • 149
  • 183
Frank
  • 2,386
  • 17
  • 26
31

I don't see a reason to use 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"
Roland
  • 127,288
  • 10
  • 191
  • 288
15
first.of.month <- ymd(format(full.date, "%Y-%m-01"))
first.of.month

[1] "2013-01-01 UTC"
nacnudus
  • 6,328
  • 5
  • 33
  • 47
2

i have another solution :

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

but it needs the library 'lubridate' or 'date.table' (aggregation with data.table)

ah bon
  • 9,293
  • 12
  • 65
  • 148
iauhs
  • 53
  • 5
2

You can simply use base R's trunc:

d <- as.POSIXct("2013-01-11 00:00:21", tz="UTC")
trunc(d, "month")
#[1] "2013-01-01 UTC"
Maël
  • 45,206
  • 3
  • 29
  • 67