First day of the month from a POSIXct date time using lubridate
Asked Answered
P

5

34

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")
Poisoning answered 12/5, 2014 at 6:51 Comment(1)
I know one way to do it, hopefully there are some smarter ways out there.Poisoning
T
76

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"
Tong answered 12/11, 2015 at 1:1 Comment(2)
Could we remove the tz?Powerdive
@Powerdive try lubridate::as_dateTong
R
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"
Rabbitry answered 12/5, 2014 at 7:15 Comment(3)
+1 for not using a string formatting hack (like me).Poisoning
Just came across this, nice way of going about it. Makes it really easy, was over complicating it also with lubridate.Candancecandela
This is also significantly faster.Manolete
P
15
first.of.month <- ymd(format(full.date, "%Y-%m-01"))
first.of.month

[1] "2013-01-01 UTC"
Poisoning answered 12/5, 2014 at 6:51 Comment(0)
H
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)

Hastie answered 26/10, 2016 at 13:42 Comment(0)
L
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"
Lindsley answered 25/4, 2022 at 19:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.