方法一:下个月第一天减去一天
1 2 3 4 5
| from datetime import date, timedelta
today = date.today() first_day_in_next_month = date(today.year, today.month + 1, 1) last_day_in_current_month = first_day_in_next_month - timedelta(days=1)
|
这种方法有个 bug,就是 12 月不能使用。
方法二:使用日历计算当月有多少天
1 2 3 4 5 6
| from calendar import monthrange from datetime import date
today = date.today() _, days_in_current_month = monthrange(today.year, today.month) last_day_in_current_month = date(today.year, today.month, days_in_current_month)
|
方法三:使用 pandas 库计算
1 2 3 4 5 6
| from datetime import date
import pandas as pd
today = date.today() last_day_in_current_month = (today + pd.offsets.MonthEnd()).date()
|
MonthEnd 有个参数,可以指定接下来第几个月。
甚至可以很方便的得到接下来 12 个月的最后一天,即使超过了当年也没有关系。
1 2 3
| for month in range(1, 13, 1): last_day = (today + pd.offsets.MonthEnd(month)).date() print(last_day)
|
虽然方法三很方便,如果你的计算中没别的地方需要 pandas,我建议使用方法二,不要因为一个非常小功能引入一个较大的包!