有没有一种方法可以使用Python的标准库轻松确定(即一个函数调用)给定月份的最后一天?
如果标准库不支持,dateutil包是否支持此功能?
有没有一种方法可以使用Python的标准库轻松确定(即一个函数调用)给定月份的最后一天?
如果标准库不支持,dateutil包是否支持此功能?
当前回答
更简单地说:
import datetime
now = datetime.datetime.now()
datetime.date(now.year, 1 if now.month==12 else now.month+1, 1) - datetime.timedelta(days=1)
其他回答
这是另一个答案。无需额外包装。
datetime.date(year + int(month/12), month%12+1, 1)-datetime.timedelta(days=1)
取下个月的第一天,从中减去一天。
我喜欢这样
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)
我的方法:
def get_last_day_of_month(mon: int, year: int) -> str:
'''
Returns last day of the month.
'''
### Day 28 falls in every month
res = datetime(month=mon, year=year, day=28)
### Go to next month
res = res + timedelta(days=4)
### Subtract one day from the start of the next month
res = datetime.strptime(res.strftime('%Y-%m-01'), '%Y-%m-%d') - timedelta(days=1)
return res.strftime('%Y-%m-%d')
>>> get_last_day_of_month(mon=10, year=2022)
... '2022-10-31'
这并不能解决主要问题,但一个获取一个月内最后一个工作日的好方法是使用calendar.monthcalendar,它返回一个日期矩阵,将星期一作为第一列,将星期日作为最后一列。
# 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
整个[0:-2]的事情就是把周末的专栏删掉,然后扔掉。月份以外的日期由0表示,因此最大值实际上忽略了这些日期。
numpy.ravel的使用并不是绝对必要的,但我讨厌仅仅依赖于numpy.ndarray.max如果不知道要在哪个轴上计算,就会使数组变平的约定。
使用datetime月包。
$ pip install datetime-month
$ python
>>> from month import XMonth
>>> Xmonth(2022, 11).last_date()
datetime.date(2022, 11, 30)