M.Alsioufi
M.Alsioufi

Reputation: 695

Have a list of hours between two dates in python

I have two times and I want to make a list of all the hours between them using the same format in Python

from= '2016-12-02T11:00:00.000Z'
to= '2017-06-06T07:00:00.000Z'
hours=to-from

so the result will be something like this 2016-12-02T11:00:00.000Z 2016-12-02T12:00:00.000Z 2016-12-02T13:00:00.000Z ..... and so on How can I so this and what kind of plugin should I use?

Upvotes: 6

Views: 11767

Answers (2)

Azat Ibrakov
Azat Ibrakov

Reputation: 11009

simpler solution using standard library's datetime package:

from datetime import datetime, timedelta

DATE_TIME_STRING_FORMAT = '%Y-%m-%dT%H:%M:%S.%fZ'

from_date_time = datetime.strptime('2016-12-02T11:00:00.000Z',
                                   DATE_TIME_STRING_FORMAT)
to_date_time = datetime.strptime('2017-06-06T07:00:00.000Z',
                                 DATE_TIME_STRING_FORMAT)

date_times = [from_date_time.strftime(DATE_TIME_STRING_FORMAT)]
date_time = from_date_time
while date_time < to_date_time:
    date_time += timedelta(hours=1)
    date_times.append(date_time.strftime(DATE_TIME_STRING_FORMAT))

will give us

>>>date_times
['2016-12-02T11:00:00.000000Z', 
 '2016-12-02T12:00:00.000000Z',
 '2016-12-02T13:00:00.000000Z', 
 '2016-12-02T14:00:00.000000Z',
 '2016-12-02T15:00:00.000000Z', 
 '2016-12-02T16:00:00.000000Z',
 '2016-12-02T17:00:00.000000Z', 
 '2016-12-02T18:00:00.000000Z',
 '2016-12-02T19:00:00.000000Z', 
 '2016-12-02T20:00:00.000000Z',
 ...]

Upvotes: 9

aquil.abdullah
aquil.abdullah

Reputation: 3157

If possible I would recommend using pandas.

import pandas
time_range = pandas.date_range('2016-12-02T11:00:00.000Z', '2017-06-06T07:00:00.000Z', freq='H')

If you need strings then use the following:

timestamps = [str(x) + 'Z' for x in time_range]
# Output
# ['2016-12-02 11:00:00+00:00Z',
#  '2016-12-02 12:00:00+00:00Z',
#  '2016-12-02 13:00:00+00:00Z',
#  '2016-12-02 14:00:00+00:00Z',
#  '2016-12-02 15:00:00+00:00Z',
#  '2016-12-02 16:00:00+00:00Z',
#  ...]

Upvotes: 13

Related Questions