代码段:
from datetime import date, timedelta
today = date.today()
last_day_of_last_month = d = date(today.year, today.month, 1) - timedelta(1)
first_day_of_last_month = date(d.year, d.month, 1)
实际代码中的函数:
import calendar
from datetime import date, timedelta
DATE_FMT = "%Y-%m-%d"
def month_day_pair(last_month=False):
"""获取字符串格式的本月初与本月底时间对(或上月初与上月底时间对)"""
today = date.today()
year, month = today.year, today.month
if last_month:
end = date(today.year, today.month, 1) - timedelta(1)
start = date(end.year, end.month, 1)
else:
start = date(year, month, 1)
_, last = calendar.monthrange(year, month)
end = date(year, month, last)
return f"{start:DATE_FMT}", f"{end:DATE_FMT}"
网友评论