Create End of the Month Date from a Date Variable

Create end of the month date from a date variable

To get the end of months you could just create a Date vector containing the 1st of all the subsequent months and subtract 1 day.

date.end.month <- seq(as.Date("2012-02-01"),length=4,by="months")-1
date.end.month
[1] "2012-01-31" "2012-02-29" "2012-03-31" "2012-04-30"

R calculate month end

You can do this with:

library(lubridate)

DATE$DATE_Month_End <- DATE$DATE
day(DATE$DATE_Month_End) <- days_in_month(DATE$DATE)

since day() <- lets you change the day while keeping the year and month.

Set a date variable that equals to previous month's full month

Here are the methods i use for this:

public static DateTime GetStartOfLastMonth(DateTime dt)
{
var date = dt.AddMonths(-1);
return new DateTime(date.Year, date.Month, 1, 0, 0, 0, DateTimeKind.Local);
}

public static DateTime GetEndOfLastMonth(DateTime dt)
{
var date = dt.AddMonths(-1);
var daysInLastMonth = DateTime.DaysInMonth(date.Year, date.Month);

return new DateTime(date.Year, date.Month, daysInLastMonth, 0, 0, 0, DateTimeKind.Local);
}

Note: depending on your case, you may want to change GetEndOfLastMonth to be 23,59,59. Since i operate in dates, this is irrelevant for the library this code is in.

End of the (next) month from a random date

Updated answer

Thanks to @Edward for pointing out the issue in the original answer.

You can use ceiling_date after adding 1 month to the original date

ceiling_date(as.Date('2019-05-15') + months(1), unit = "month") - 1
#[1] "2019-06-30"

ceiling_date(as.Date('2019-04-15') + months(1), unit = "month") - 1
#[1] "2019-05-31"

Old Answer

We can use ceiling_date with unit as '2 months'

library(lubridate)
'2019-05-15' %>% as.Date() %>% ceiling_date(unit = '2 months') - 1
#[1] "2019-06-30"

Getting last day of the month in a given string date


Java 8 and above.

By using convertedDate.getMonth().length(convertedDate.isLeapYear()) where convertedDate is an instance of LocalDate.

String date = "1/13/2012";
LocalDate convertedDate = LocalDate.parse(date, DateTimeFormatter.ofPattern("M/d/yyyy"));
convertedDate = convertedDate.withDayOfMonth(
convertedDate.getMonth().length(convertedDate.isLeapYear()));

Java 7 and below.

By using getActualMaximum method of java.util.Calendar:

String date = "1/13/2012";
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
Date convertedDate = dateFormat.parse(date);
Calendar c = Calendar.getInstance();
c.setTime(convertedDate);
c.set(Calendar.DAY_OF_MONTH, c.getActualMaximum(Calendar.DAY_OF_MONTH));

Last Day of Month Function, given Year and Month

Here are two solutions. Both work even if year and month are vectors instead of the scalars shown here.

1) as.Date.yearmon First convert the input to a "yearmon" object and then convert that to "Date" class using as.Date with the frac=1 argument.

library(zoo)

# input
year <- 2018
month <- 2

ym <- as.yearmon(paste(year, month, sep = "-"))
as.Date(ym, frac = 1)
## [1] [1] "2018-02-28"

2) base A base solution using fom (first of month) from Find out the number of days of a month in R is the following. First we convert the year and month to a "Date" class object dat1 for the first of that month and add 32 which is enough days to get to the next month. Then use fom to find the first of that month and subtract 1 to get the last date of the input year/month.

fom <- function(x) as.Date(cut(x, "month"))

dat1 <- as.Date(paste(year, month, 1, sep = "-"))
fom(dat1 + 32) - 1
## [1] "2018-02-28"

Change date to the last day of month using days_in_month

This is a great question, because it's been asked many times!
Check out these answers:

R calculate month end

Create end of the month date from a date variable

The great part? Packages update all the time, so sometimes the answers no longer work. That's not the case here.

@Edgar Santos, at the first link, gave a detailed answer that fits your question perfectly.

library(lubridate)

dt <- c("2017-01","2017-02") # data
dt <- ym(dt) # change to date of year-month format
day(dt) <- days_in_month(dt) # update the 'day' in the date

[1] "2017-01-31" "2017-02-28"

Find the end of the month of a Pandas DataFrame Series

You can use pandas.tseries.offsets.MonthEnd:

from pandas.tseries.offsets import MonthEnd

df['Date'] = pd.to_datetime(df['Date'], format="%Y%m") + MonthEnd(1)

The 1 in MonthEnd just specifies to move one step forward to the next date that's a month end. (Using 0 or leaving it blank would also work in your case). If you wanted the last day of the next month, you'd use MonthEnd(2), etc. This should work for any month, so you don't need to know the number days in the month, or anything like that. More offset information can be found in the documentation.

Example usage and output:

df = pd.DataFrame({'Date': [200104, 200508, 201002, 201602, 199912, 200611]})
df['EndOfMonth'] = pd.to_datetime(df['Date'], format="%Y%m") + MonthEnd(1)

Date EndOfMonth
0 200104 2001-04-30
1 200508 2005-08-31
2 201002 2010-02-28
3 201602 2016-02-29
4 199912 1999-12-31
5 200611 2006-11-30

Using existing “Date” variable; add month and week variables to the data frame

The syntax that you were looking for is :

library(dplyr)

Covid19_df <- Covid19_df %>%
mutate(Month = lubridate::month(Date),
Week = lubridate::week(Date))


Related Topics



Leave a reply



Submit