Have a list of hours between two dates in python

感情迁移 提交于 2019-12-11 04:48:11

问题


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?


回答1:


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',
#  ...]



回答2:


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',
 ...]


来源:https://stackoverflow.com/questions/44683774/have-a-list-of-hours-between-two-dates-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!