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 18:45

If you pass in a date range, you can use this:

def last_day_of_month(any_days):
    res = []
    for any_day in any_days:
        nday = any_day.days_in_month -any_day.day
        res.append(any_day + timedelta(days=nday))
    return res
查看更多
大哥的爱人
3楼-- · 2018-12-31 18:45

Here is another answer. No extra packages required.

datetime.date(year + int(month/12), (month+1)%12, 1)-datetime.timdelta(days=1)

Get the first day of the next month and subtract a day from it.

查看更多
春风洒进眼中
4楼-- · 2018-12-31 18:50

If you want to make your own small function, this is a good starting point:

def eomday(year, month):
    """returns the number of days in a given month"""
    days_per_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    d = days_per_month[month - 1]
    if month == 2 and (year % 4 == 0 and year % 100 != 0 or year % 400 == 0):
        d = 29
    return d

For this you have to know the rules for the leap years:

  • every fourth year
  • with the exception of every 100 year
  • but again every 400 years
查看更多
墨雨无痕
5楼-- · 2018-12-31 18:54

For me it's the simplest way:

selected_date = date(some_year, some_month, some_day)

if selected_date.month == 12: # December
     last_day_selected_month = date(selected_date.year, selected_date.month, 31)
else:
     last_day_selected_month = date(selected_date.year, selected_date.month + 1, 1) - timedelta(days=1)
查看更多
栀子花@的思念
6楼-- · 2018-12-31 18:55
import datetime

now = datetime.datetime.now()
start_month = datetime.datetime(now.year, now.month, 1)
date_on_next_month = start_month + datetime.timedelta(35)
start_next_month = datetime.datetime(date_on_next_month.year, date_on_next_month.month, 1)
last_day_month = start_next_month - datetime.timedelta(1)
查看更多
只靠听说
7楼-- · 2018-12-31 18:57

I didn't notice this earlier when I was looking at the documentation for the calendar module, but a method called monthrange provides this information:

monthrange(year, month)
    Returns weekday of first day of the month and number of days in month, for the specified year and month.

>>> import calendar
>>> calendar.monthrange(2002,1)
(1, 31)
>>> calendar.monthrange(2008,2)
(4, 29)
>>> calendar.monthrange(2100,2)
(0, 28)

so:

calendar.monthrange(year, month)[1]

seems like the simplest way to go.

Just to be clear, monthrange supports leap years as well:

>>> from calendar import monthrange
>>> monthrange(2012, 2)
(2, 29)

My previous answer still works, but is clearly suboptimal.

查看更多
登录 后发表回答