Python:如何在两个日期时间之间获得几分钟的时间(例如工作日的晚上,周末,假期)?


import datetime as dt
night_hours = [18, 19, 20, 21, 22, 23, 24, 0, 1, 2, 3, 4, 5, 6]
holidays = ["2023-04-01", "2023-04-05", "2023-04-11"]
dt_fmt = "%Y-%m-%d %H:%M"
start_dt = dt.strptime("2023-04-01 12:00", dt_fmt)
end_dt = dt.strptime("2023-04-15 23:00", dt_fmt)
minutes_of_all_workday_nights = ???
minutes_of_all_the_weekends = ???
minutes_of_all_the_holidays = ???

如何获得Python中最后三个变量的值?

从开始日期到结束日期的简单循环,步骤为1分钟和3个不同的计数器应该可以满足您的要求。看看这个:

current_dt = start_dt
while current_dt <= end_dt:
if current_dt.weekday() < 5 and current_dt.hour in night_hours:
minutes_of_all_workday_nights += 1

if current_dt.weekday() >= 5:
minutes_of_all_the_weekends += 1

if current_dt.date().isoformat() in holidays:
minutes_of_all_the_holidays += 1

current_dt += dt.timedelta(minutes=1)
print(minutes_of_all_workday_nights)
print(minutes_of_all_the_weekends)
print(minutes_of_all_the_holidays)

相关内容

  • 没有找到相关文章

最新更新