gpt4 book ai didi

python - 在 Python 中循环用户定义的日期

转载 作者:行者123 更新时间:2023-12-04 07:32:46 25 4
gpt4 key购买 nike

我已经对此进行了一些搜索,但还没有完全找到适用于我需要做的事情的东西。如果这是 PHP,我想我可能已经弄清楚了。但我对 Python 完全陌生。
我有一个爬行脚本,我希望用户能够输入一年和一个月。然后脚本将循环遍历每个月(如果提供多个​​)然后每年(如果提供多个​​)。两个变量FiledStartDateFiledEndDate必须存在,因为它们是通过 post 请求中的有效负载发送的。
我可以用一年零一个月的时间让它发挥作用。但是,我需要超越单一的年月。
注:我没有忘记闰年。如果有人可以包含它,那就太好了。否则,我认为通过工作代码,我可以弄清楚如何处理它。
显然,下面的示例代码不起作用。但希望它展示了我想做的事情。
提前致谢

years = '2020'
months = ['01', '02', '03']

for year in years:
for month in months:
if month == '01':
FiledStartDate = year + '-01-01'
FiledEndDate = year + '-01-31'

if month == '02':
FiledStartDate = year + '-02-01'
FiledEndDate = year + '-02-28'

if month == '03':
FiledStartDate = year + '-03-01'
FiledEndDate = year + '-03-31'

if month == '04':
FiledStartDate = year + '-04-01'
FiledEndDate = year + '-04-30'

do(something)
redo(something)

最佳答案

当然你需要考虑不正确的输入,如果发生这种情况(异常(exception)),否则简单的解决方案

from datetime import datetime, timedelta
years = ['2020']
months = ['01', '02', '03']

for year in years:
for month in months:
FiledStartDate = datetime(int(year), int(month), 1)
FiledEndDate = datetime(int(year), int(month) + 1, 1) - timedelta(1)
print(FiledStartDate, FiledEndDate)
...
2020-01-01 00:00:00 2020-01-31 00:00:00
2020-02-01 00:00:00 2020-02-29 00:00:00
2020-03-01 00:00:00 2020-03-31 00:00:00

关于python - 在 Python 中循环用户定义的日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67872753/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com