Python: iterate through two datetimes hourly

后端 未结 1 1368
忘了有多久
忘了有多久 2021-01-23 02:33

Here\'s the question:

Using python\'s datetime module, create an iterator that generates all the hours between two datetime.datatime objects.

it = hourly_i

相关标签:
1条回答
  • 2021-01-23 03:13

    I'm almost sure this is school work you got there.

    But I'll give you some reading on python's iterator protocol, and short and sweet example maybe you get it; and its not rocket science anyway.

    The Iterator Protocol: How “For Loops” Work in Python

    >>> from datetime import datetime, timedelta
    >>> def hourly_it(start, finish):
    ...     while finish > start:
    ...             start = start + timedelta(hours=1)
    ...             yield start
    >>> start = datetime(2018, 10, 2, 12)
    >>> finish = datetime(2018, 10, 3, 12)
    >>> for hour in hourly_it(start, finish):
    ...     print(hour)
    ...
    2018-10-02 13:00:00
    2018-10-02 14:00:00
    2018-10-02 15:00:00
    2018-10-02 16:00:00
    2018-10-02 17:00:00
    2018-10-02 18:00:00
    2018-10-02 19:00:00
    2018-10-02 20:00:00
    2018-10-02 21:00:00
    2018-10-02 22:00:00
    2018-10-02 23:00:00
    2018-10-03 00:00:00
    2018-10-03 01:00:00
    2018-10-03 02:00:00
    2018-10-03 03:00:00
    2018-10-03 04:00:00
    2018-10-03 05:00:00
    2018-10-03 06:00:00
    2018-10-03 07:00:00
    2018-10-03 08:00:00
    2018-10-03 09:00:00
    2018-10-03 10:00:00
    2018-10-03 11:00:00
    2018-10-03 12:00:00
    
    0 讨论(0)
提交回复
热议问题