Get Last Day of the Month in Python

2018-12-31 18:43发布

Is there a way using Python's standard library to easily determine (i.e. one function call) the last day of a given month?

If the standard library doesn't support that, does the dateutil package support this?

标签: python date
27条回答
余生请多指教
2楼-- · 2018-12-31 19:01

I prefer this way

import datetime
import calendar

date=datetime.datetime.now()
month_end_date=datetime.datetime(date.year,date.month,1) + datetime.timedelta(days=calendar.monthrange(date.year,date.month)[1] - 1)
查看更多
时光乱了年华
3楼-- · 2018-12-31 19:04

This does not address the main question, but one nice trick to get the last weekday in a month is to use calendar.monthcalendar, which returns a matrix of dates, organized with Monday as the first column through Sunday as the last.

# Some random date.
some_date = datetime.date(2012, 5, 23)

# Get last weekday
last_weekday = np.asarray(calendar.monthcalendar(some_date.year, some_date.month))[:,0:-2].ravel().max()

print last_weekday
31

The whole [0:-2] thing is to shave off the weekend columns and throw them out. Dates that fall outside of the month are indicated by 0, so the max effectively ignores them.

The use of numpy.ravel is not strictly necessary, but I hate relying on the mere convention that numpy.ndarray.max will flatten the array if not told which axis to calculate over.

查看更多
回忆,回不去的记忆
4楼-- · 2018-12-31 19:07
from datetime import timedelta
(any_day.replace(day=1) + timedelta(days=32)).replace(day=1) - timedelta(days=1)
查看更多
伤终究还是伤i
5楼-- · 2018-12-31 19:08

This is actually pretty easy with dateutil.relativedelta (package python-datetutil for pip). day=31 will always always return the last day of the month.

Example:

from datetime import datetime
from dateutil.relativedelta import relativedelta

date_in_feb = datetime.datetime(2013, 2, 21)
print datetime.datetime(2013, 2, 21) + relativedelta(day=31)  # End-of-month
>>> datetime.datetime(2013, 2, 28, 0, 0)
查看更多
回忆,回不去的记忆
6楼-- · 2018-12-31 19:09

EDIT: see my other answer. It has a better implementation than this one, which I leave here just in case someone's interested in seeing how one might "roll your own" calculator.

@John Millikin gives a good answer, with the added complication of calculating the first day of the next month.

The following isn't particularly elegant, but to figure out the last day of the month that any given date lives in, you could try:

def last_day_of_month(date):
    if date.month == 12:
        return date.replace(day=31)
    return date.replace(month=date.month+1, day=1) - datetime.timedelta(days=1)

>>> last_day_of_month(datetime.date(2002, 1, 17))
datetime.date(2002, 1, 31)
>>> last_day_of_month(datetime.date(2002, 12, 9))
datetime.date(2002, 12, 31)
>>> last_day_of_month(datetime.date(2008, 2, 14))
datetime.date(2008, 2, 29)
查看更多
妖精总统
7楼-- · 2018-12-31 19:09
import calendar
from time import gmtime, strftime
calendar.monthrange(int(strftime("%Y", gmtime())), int(strftime("%m", gmtime())))[1]

Output:

31



This will print the last day of whatever the current month is. In this example it was 15th May, 2016. So your output may be different, however the output will be as many days that the current month is. Great if you want to check the last day of the month by running a daily cron job.

So:

import calendar
from time import gmtime, strftime
lastDay = calendar.monthrange(int(strftime("%Y", gmtime())), int(strftime("%m", gmtime())))[1]
today = strftime("%d", gmtime())
lastDay == today

Output:

False

Unless it IS the last day of the month.

查看更多
登录 后发表回答