Python: How to get minutes of time (e.g. night of workdays, weekends, holidays) between two datetimes?

huangapple go评论68阅读模式
英文:

Python: How to get minutes of time (e.g. night of workdays, weekends, holidays) between two datetimes?

问题

You can obtain the values of the last three variables in Python as follows:

# Calculate minutes_of_all_workday_nights
minutes_of_all_workday_nights = sum([(end_dt - start_dt).total_seconds() / 60 for i in range(7, 15) for start_hour in night_hours])

# Calculate minutes_of_all_the_weekends
minutes_of_all_the_weekends = sum([(end_dt - start_dt).total_seconds() / 60 for i in range(7) for start_hour in night_hours])

# Calculate minutes_of_all_the_holidays
minutes_of_all_the_holidays = sum([(end_dt - start_dt).total_seconds() / 60 for holiday in holidays])

# Now, the three variables hold the calculated values.

Please note that you should place this code within the appropriate context in your Python script.

英文:
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 = ???

How can I get the values of the last three variables in Python?

答案1

得分: 1

从起始日期到结束日期,以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)

如果您有其他问题,请随时提出。

英文:

A simple loop from start date to end date with a step of 1 min and 3 different counters should do the trick for you. Check this out:

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)

huangapple
  • 本文由 发表于 2023年4月10日 18:43:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/75976398.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定