2024-06-25 22:55:43 发布
网友
我正在尝试使用python查找前五个月的第一个和最后一个日期
today = datetime.today() first = today.replace(day=1) lastMonth = first - timedelta(days=153)
现在,如何在python中查找前五个月的第一个和最后一个日期
有人能帮我吗
以下是基于一个已有的两个答案。它增加了在一系列日期内对第一天和最后一天做出响应的能力
Get year month for last X months
How to get the first and last day of the month
import calendar import datetime from dateutil.relativedelta import relativedelta def get_last_months(start_date, months): for i in range(months): _, num_days = calendar.monthrange(start_date.year,start_date.month) first_day = datetime.date(start_date.year, start_date.month, 1).strftime('%Y-%m-%d') last_day = datetime.date(start_date.year, start_date.month, num_days).strftime('%Y-%m-%d') yield (first_day, last_day) start_date += relativedelta(months = -1) months_back = 5 print([i for i in get_last_months(datetime.datetime.today(), months_back)])
输出:
[('2020-10-01', '2020-10-31'), ('2020-09-01', '2020-09-30'), ('2020-08-01', '2020-08-31'), ('2020-07-01', '2020-07-31'), ('2020-06-01', '2020-06-30')]
以下是基于一个已有的两个答案。它增加了在一系列日期内对第一天和最后一天做出响应的能力
Get year month for last X months
How to get the first and last day of the month
输出:
相关问题 更多 >
编程相关推荐