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

℡╲_俬逩灬. 提交于 2020-01-10 02:29:23

问题


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")

回答1:


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"



回答2:


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"



回答3:


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

[1] "2013-01-01 UTC"



回答4:


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)



来源:https://stackoverflow.com/questions/23602706/first-day-of-the-month-from-a-posixct-date-time-using-lubridate

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!