gpt4 book ai didi

python - 计算两个日期之间的星期几小时对

转载 作者:太空狗 更新时间:2023-10-29 21:34:05 26 4
gpt4 key购买 nike

考虑以下 24H 格式的day-of-week-hour 对列表:

{
'Mon': [9,23],
'Thu': [12, 13, 14],
'Tue': [11, 12, 14],
'Wed': [11, 12, 13, 14]
'Fri': [13],
'Sat': [],
'Sun': [],
}

和两个时间点,例如:

  • 开始:

    datetime.datetime(2015, 7, 22, 17, 58, 54, 746784)
  • 结束:

    datetime.datetime(2015, 8, 30, 10, 22, 36, 363912)

假设我们需要知道对于上面指定的每个day-of-week-hour 对,这两个日期时间之间有多少小时(向上或向下舍入)。

如何在 Python 中解决这个问题?我在一般的详细级别上探索了 timedeltarelativedelta,但我没有找到任何可以提供接近于此的内容。

为简单起见,我们可以假设所有内容都指代同一时区。


也许一个更简单的问题是关注单个天-小时对,例如两个任意日期时间之间有多少个星期三:14

最佳答案

也许是这样的:

from calendar import day_abbr
from datetime import datetime, timedelta


def solve(start, end, data):
days = list(day_abbr)
output = dict.fromkeys(days, 0)

while start <= end:
day = days[start.weekday()]
if start.hour in data[day]:
output[day] += 1
start = start + timedelta(minutes=60)

return output


data = {
'Mon': [9, 23],
'Thu': [12, 13, 14],
'Tue': [11, 12, 14],
'Wed': [11, 12, 13, 14],
'Fri': [13],
'Sat': [],
'Sun': [],
}

start = datetime(2015, 7, 22, 17, 58, 54, 746784)
end = datetime(2015, 8, 30, 10, 22, 36, 363912)

print solve(start, end, data)
# {'Wed': 20, 'Sun': 0, 'Fri': 6, 'Tue': 15, 'Mon': 10, 'Thu': 18, 'Sat': 0}

按小时获取每一天的计数:

from calendar import day_abbr
from collections import defaultdict
from datetime import datetime, timedelta
from pprint import pprint


def solve(start, end, data):
days = list(day_abbr)
output = defaultdict(lambda: defaultdict(int))

while start <= end:
day = days[start.weekday()]
if start.hour in data[day]:
output[day][start.hour] += 1
start = start + timedelta(minutes=60)
return {k: dict(v) for k, v in output.items()}


data = {
'Mon': [9, 23],
'Thu': [12, 13, 14],
'Tue': [11, 12, 14],
'Wed': [11, 12, 13, 14],
'Fri': [13],
'Sat': [],
'Sun': [],
}

start = datetime(2015, 7, 22, 17, 58, 54, 746784)
end = datetime(2015, 8, 30, 10, 22, 36, 363912)

pprint(solve(start, end, data))
# output
{'Fri': {13: 6},
'Mon': {9: 5, 23: 5},
'Thu': {12: 6, 13: 6, 14: 6},
'Tue': {11: 5, 12: 5, 14: 5},
'Wed': {11: 5, 12: 5, 13: 5, 14: 5}}

关于python - 计算两个日期之间的星期几小时对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31574971/

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