如何在 Python 中为给定日期的每个小时生成 datetime
此示例代码为给定时区中给定日期的每个小时生成时区感知的 datetime(分钟和秒始终设置为 0)。
首先,安装 UliEngineering 库和用于时区的 pytz:
install_uliengineering.sh
pip install --user UliEngineering pytz现在你可以使用 UliEngineering.Utils.Date.yield_hours_on_day():
yield_hours_example.py
from UliEngineering.Utils.Date import *
for hour in yield_hours_on_day(year=2022, month=6, day=15, tz=pytz.timezone("Europe/Berlin"):
pass # TODO: 你的代码放在这里或者,如果你想要 datetime 实例的 list 而不是生成器:
yield_hours_list_example.txt
from UliEngineering.Utils.Date import *
hours = list(yield_hours_on_day(year=2022, month=6, day=15, tz=pytz.timezone("Europe/Berlin")))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