如何使用 Python 迭代一年中的所有日子
要使用 Python 迭代一年中的所有日子,你可以使用此函数代码片段:
all_dates_in_year.py
from collections import namedtuple
from calendar import monthrange
Date = namedtuple("Date", ["year", "month", "day"])
def all_dates_in_year(year=2019):
for month in range(1, 13): # 月份始终是 1..12
for day in range(1, monthrange(year, month)[1] + 1):
yield Date(year, month, day)用法示例:
all_dates_example.py
for date in all_dates_in_year(2019):
print(date)这将打印(摘录):
all_dates_output.txt
Date(year=2019, month=1, day=1)
Date(year=2019, month=1, day=2)
Date(year=2019, month=1, day=3)
[...]
Date(year=2019, month=2, day=27)
Date(year=2019, month=2, day=28)
Date(year=2019, month=3, day=1)
[...]
Date(year=2019, month=12, day=29)
Date(year=2019, month=12, day=30)
Date(year=2019, month=12, day=31)你也可以使用 pip install -U UliEngineering 安装我的 Python3 库 UliEngineering,然后像这样导入使用 all_dates_in_year():
all_dates_uliengineering.py
from UliEngineering.Utils.Date import *Check out similar posts by category:
Python
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow