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

时间:2015-07-22 22:15:25

标签: python datetime python-3.x timedelta

24H格式考虑以下星期几小时对列表:

{
 '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)
    

假设我们需要知道上面指定的每个星期几小时对的这两个日期时间(向上或向下舍入)之间有多少小时。

如何在Python中解决此问题?我在一般细节层面上探讨了timedeltarelativedelta,但我没有找到能够提供与此类似的东西。

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

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

5 个答案:

答案 0 :(得分:4)

也许是这样的:

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}}

答案 1 :(得分:2)

也许我没有完全理解你的问题,但你可以在两个日期之间得到所有的时间,并总结两个日期之间每小时和每天出现的次数:

from datetime import datetime
from dateutil import  rrule,parser


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

st = datetime(2015, 7, 22, 17, 58, 54, 746784)

ed = datetime(2015, 8, 30, 10, 22, 36, 363912)
dates = list(rrule.rrule(rrule.HOURLY,
                         dtstart=parser.parse(st.strftime("%Y-%m-%d %H:%M:%S")),
                         until=parser.parse(ed.strftime("%Y-%m-%d %H:%M:%S"))))


days = {"Mon":0,"Tue": 1,"Wed":2,"Thu": 3,"Fri":4,"Sat":5,"Sun":6}

for k, val in d.items():
    for v in val:
        print("day: {} hour: {}".format(k,v))
        day = days[k]
        print(sum((v == dt.hour and dt.weekday() == day) for dt in dates))

输出:

day: Wed hour: 11
5
day: Wed hour: 12
5
day: Wed hour: 13
5
day: Wed hour: 14
5
day: Fri hour: 13
6
day: Tue hour: 11
5
day: Tue hour: 12
5
day: Tue hour: 14
5
day: Mon hour: 9
6
day: Mon hour: 23
5
day: Thu hour: 12
5
day: Thu hour: 13
5
day: Thu hour: 14
5

不确定您是希望每个列表中所有小时的总和还是每个小时的总时数,但无论哪种方式都可以将输出存储在dict中。

counts = {'Thu':{}, 'Sun':{}, 'Fri':{}, 'Mon':{}, 'Tue':{}, 'Sat':{}, 'Wed':{}}
for k, val in d.items():
    for v in val:
        day = days[k]
        sm = sum((v == dt.hour and dt.weekday() == day) for dt in dates)
        counts[k][v] = sm

from pprint import pprint as pp
pp(counts)

输出:

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

答案 2 :(得分:2)

这是一个包含循环和datetime的解决方案:

import datetime

pairs = {1: [9,23],
2: [11, 12, 14],
3: [11, 12, 13, 14],
4: [12, 13, 14],
5: [13],
6: [],
7: []
}

start = datetime.datetime(2015, 7, 22, 17, 58, 54, 746784)
end = datetime.datetime(2015, 8, 30, 10, 22, 36, 363912)
result={}
for d,hl in pairs.items():
    for h in hl:
        result[(d,h)] = 0
        for diff in range((end-start).days*24):
            comp = start + datetime.timedelta(hours=diff)
            if comp.isoweekday() == d and comp.hour == h:
                result[(d,h)] += 1

>>> result
{(3, 12): 5, (5, 13): 6, (3, 13): 5, (1, 23): 5, (2, 11): 5, (3, 11): 5, (4, 14): 6, (4, 13): 6, (4, 12): 6, (2, 12): 5, (2, 14): 5, (3, 14): 5, (1, 9): 5}

我还会尝试使用timestamp()%的解决方案。

答案 3 :(得分:2)

以下是算术的另一种解决方案:

import datetime

pairs = {1: [9,23],
2: [11, 12, 14],
3: [11, 12, 13, 14],
4: [12, 13, 14],
5: [13],
6: [],
7: []
}

start = datetime.datetime(2015, 7, 22, 17, 58, 54, 746784)
end = datetime.datetime(2015, 8, 30, 10, 22, 36, 363912)
result={}
weeks = (end-start).days//7

for d,hl in pairs.items():
    for h in hl:
        initial = weeks
        if d > start.isoweekday() or (
           d == start.isoweekday() and h >= start.hour):
            initial += 1
        result[(d,h)] = initial

>>> for k in sorted(result):
...     print(k, result[k])
...
(1, 9) 5
(1, 23) 5
(2, 11) 5
(2, 12) 5
(2, 14) 5
(3, 11) 5
(3, 12) 5
(3, 13) 5
(3, 14) 5
(4, 12) 6
(4, 13) 6
(4, 14) 6
(5, 13) 6

答案 4 :(得分:0)

所以,如果我正确地理解了你的问题,我会首先在时间范围内找到“小时”的第一次出现,然后逐周寻找下一次出现。像这样:

#!/usr/bin/python
from __future__ import print_function
import datetime
import dateutil.relativedelta


def hours_between(start, end, weekday, hour):
    first = start + dateutil.relativedelta.relativedelta(
        weekday=weekday, hour=hour,
        minute=0, second=0, microsecond=0)
    week = dateutil.relativedelta.relativedelta(weeks=1)

    all_dates = []
    d = first
    while d < end:
        all_dates.append(d)
        d += week

    return all_dates


def main():
    start = datetime.datetime(2015, 7, 22, 17, 58, 54, 746784)
    end = datetime.datetime(2015, 8, 30, 10, 22, 36, 363912)
    all_dates = hours_between(start, end, dateutil.relativedelta.WE, 14)
    print(all_dates)
    print(len(all_dates))

main()