how can i easily generate utc timestamps by hour between two dates using python?

import datetime
from datetime import datetime, timedelta

timestamp_format = '%Y-%m-%dT%H:%M:%S%z'

earliest_ts_str = '2020-10-01T00:00:00Z'
ts_obj = datetime.strptime(earliest_ts_str, timestamp_format)

latest_ts_str = '2020-10-02T00:00:00Z'
latest_ts_obj = datetime.strptime(latest_ts_str, timestamp_format)

ts_raw = []
while ts_obj <= latest_ts_obj:
    ts_raw.append(ts_obj)
    ts_obj += timedelta(hours=1)

dates_formatted = [d.strftime('%Y-%m-%dT%H:%M:%SZ') for d in ts_raw]
print(dates_formatted)

EDIT:

Here is example with Maya

import maya

earliest_ts_str = '2020-10-01T00:00:00Z'
latest_ts_str = '2020-10-02T00:00:00Z'
start = maya.MayaDT.from_iso8601(earliest_ts_str)
end = maya.MayaDT.from_iso8601(latest_ts_str)

# end is not included, so we add 1 second
my_range = maya.intervals(start=start, end=end.add(seconds=1), interval=60*60)
dates_formatted = [d.iso8601() for d in my_range]
print(dates_formatted)

Both output

['2020-10-01T00:00:00Z',
 '2020-10-01T01:00:00Z',
 ... some left out ...
 '2020-10-01T23:00:00Z',
 '2020-10-02T00:00:00Z']

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top