如何花几个月的时间作为输入,然后确定每个月的开始日期和结束日期?我也想从2021年12月至2022年4月去
这是我到目前为止的代码:
from calendar import isleap
import datetime
year =2021
month= 4
year2=2022
months_choices=[]
for i in range(1, 5):
month = datetime.date(2021, i, 1).strftime('%b')
startDate = f"01-Dec-{year}"
if month in ["Jan", "Mar", "May", "Jul", "Aug", "Oct", "Dec"]:
endDate = f"31-{month}-{year}"
elif month in ["Apr", "Jun", "Sep", "Nov"]:
endDate = f"30-{month}-{year}"
else:
isLeap = isleap(1900)
if isLeap:
endDate = f"29-{month}-{year}"
else:
endDate = f"28-{month}-{year}"
months_choices.append((startDate, endDate))
print(months_choices)
我希望输出打印为[('01 -dec-Dec-2021','31 -Dec-2021'),('01 -Jan-2022','01 -Jan-2022','31 -Jan-- 2022'),('01 -Feb-2022','28 -Feb-2022'),('01 -March-2021','31 -March-2021'),('01-April-2021','','' 30-apr-2021')],但它像下面一样打印。
print(months_choices)
[('01-Dec-2021', '31-Jan-2021'), ('01-Dec-2021', '28-Feb-2021'), ('01-Dec-2021', '31-Mar-2021'), ('01-Dec-2021', '30-Apr-2021')]
This is the code I have so far:
from calendar import isleap
import datetime
year =2021
month= 4
year2=2022
months_choices=[]
for i in range(1, 5):
month = datetime.date(2021, i, 1).strftime('%b')
startDate = f"01-Dec-{year}"
if month in ["Jan", "Mar", "May", "Jul", "Aug", "Oct", "Dec"]:
endDate = f"31-{month}-{year}"
elif month in ["Apr", "Jun", "Sep", "Nov"]:
endDate = f"30-{month}-{year}"
else:
isLeap = isleap(1900)
if isLeap:
endDate = f"29-{month}-{year}"
else:
endDate = f"28-{month}-{year}"
months_choices.append((startDate, endDate))
print(months_choices)
I would like my output to print as [('01-Dec-2021', '31-Dec-2021'), ('01-Jan-2022', '31-Jan-2022'), ('01-Feb-2022', '28-Feb-2022'), ('01-March-2021', '31-March-2021'),('01-April-2021', '30-Apr-2021')], but it prints like below.
print(months_choices)
[('01-Dec-2021', '31-Jan-2021'), ('01-Dec-2021', '28-Feb-2021'), ('01-Dec-2021', '31-Mar-2021'), ('01-Dec-2021', '30-Apr-2021')]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
日历模块具有您可以使用的一些非常有用的功能。
作为出发点,您将受益于获得开始月/年/年末/年度的功能。
这样的东西:
输出:
The calendar module has some very useful features that you could utilise.
As a starting point you would benefit from having a function that takes the start month/year and end month/year.
Something like this:
Output:
根据评论中的要求进行编辑
,为了生成两个日期之间的日期范围,可以像这样调整解决方案:
原始解决方案
使用
calendar.monthrange(年,月份)
以获取的最后一天一个月。它为您处理了leap年。输出:
EDIT
As requested in the comments, in order to generate the date range between two dates, the solution can be adjusted like this:
Original solution
Use
calendar.monthrange(YEAR, MONTH)
to get the last day of the month. It handles the leap years for you.Output: