使用python datetime在早上9点到晚上6点之间划分时间到3小时的时间间隔

时间:2017-05-03 11:01:35

标签: python datetime

基本上,我要做的是将早上9点到晚上6点之间的时间分成指定的时间间隔

例如,如果我将时间间隔间隔指定为3小时,那么我应该通过将时间间隔在9到6之间来得到结果

['2017-05-03 09:00', '2017-05-03 12:00', '2017-05-03 15:00', '2017-05-03 18:00']

如果我将时间间隔指定为2小时,那么我应该

['2017-05-03 09:00', '2017-05-03 11:00', '2017-05-03 13:00', '2017-05-03 15:00', '2017-05-03 17:00']

以下是我的代码

from datetime import datetime
from datetime import timedelta
start_time = datetime.now().replace(hour=9, minute=0) #(Morning 9 AM)
end_time = start_time + timedelta(hours=9) # (Evening 6 PM)

result = []
time_interval = 3
while start_time <=end_time:
    result.append(start_time)
    start_time += timedelta(hours=time_interval)

print(result)

基本上,我在上面的代码中使用了while来检查条件,因此可以在不使用while语句和使用列表推导等使用其他逻辑的情况下执行相同的上述逻辑。 ?

如果可能,我还需要输出列表

[
'2017-05-03 09:00 to 2017-05-03 12:00', 
'2017-05-03 12:00 to 2017-05-03 15:00', 
'2017-05-03 15:00 to 2017-05-03 18:00'
]

2 个答案:

答案 0 :(得分:0)

或者,您可以使用rrule() from dateutil解决问题,以便每小时生成指定范围内的日期时间,然后使用指定的step迭代结果:

from datetime import datetime
from datetime import timedelta
from itertools import islice

from dateutil.rrule import HOURLY, rrule

interval = 3
start_time = datetime.now().replace(hour=9, minute=0) #(Morning 9 AM)
end_time = start_time + timedelta(hours=9) # (Evening 6 PM)

stops = islice(rrule(freq=HOURLY, dtstart=start_time, until=end_time), None, None, interval)
print([datetime.strftime(stop, "%Y-%d-%m %H:%M") for stop in stops])

打印:

['2017-05-03 09:00', '2017-05-03 12:00', '2017-05-03 15:00', '2017-05-03 18:00']

请注意,此处的列表推导和strftime()调用仅用于演示目的 - stops是一个迭代器,&#34;包含&#34;期望的datetimes

并且,使用与@NiL相同的pairwise助手,我们可以获得您想要的下一个输出:

from datetime import datetime
from datetime import timedelta
from itertools import islice, tee

from dateutil.rrule import HOURLY, rrule


def pairwise(iterable):
    """s -> (s0,s1), (s1,s2), (s2, s3), ...

    https://docs.python.org/2/library/itertools.html
    """
    a, b = tee(iterable)
    next(b, None)
    return zip(a, b)


interval = 3
start_time = datetime.now().replace(hour=9, minute=0) #(Morning 9 AM)
end_time = start_time + timedelta(hours=9) # (Evening 6 PM)

stops = islice(rrule(freq=HOURLY, dtstart=start_time, until=end_time), None, None, interval)

print(['{0} to {1}'.format(datetime.strftime(start, "%Y-%d-%m %H:%M"),
                           datetime.strftime(stop, "%Y-%d-%m %H:%M"))
       for start, stop in pairwise(stops)])

打印:

['2017-03-05 09:00 to 2017-03-05 12:00', '2017-03-05 12:00 to 2017-03-05 15:00', '2017-03-05 15:00 to 2017-03-05 18:00']

答案 1 :(得分:0)

这样的事情可能会做你想要的事情

from datetime import datetime
from datetime import timedelta
from itertools import tee
start_time = datetime.now().replace(hour=9, minute=0)  # (Morning 9 AM)
end_time = start_time + timedelta(hours=9)  # (Evening 6 PM)

time_interval = 3
delta = 9  # hours


def pairwise(iterable):
    """s -> (s0,s1), (s1,s2), (s2, s3), ...

    https://docs.python.org/2/library/itertools.html
    """
    a, b = tee(iterable)
    next(b, None)
    return zip(a, b)


iterations = (delta // time_interval) + 1
result = [start_time+i*timedelta(hours=time_interval)
          for i in range(iterations)]
print(result)

formatted=['{} to {}'.format(
    start.strftime('%Y-%m-%d %H:%M'),
    end.strftime('%Y-%m-%d %H:%M'))
    for start, end in pairwise(result)]

from pprint import pprint
pprint(formatted)