Skip to main content
 首页 » 编程设计

python之在 python 中列出两个日期之间的小时数

2025年05月04日13lhb25

我有两次,我想在 Python 中使用相同的格式列出它们之间的所有时间

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

所以结果会是这样的 2016-12-02T11:00:00.000Z 2016-12-02T12:00:00.000Z 2016-12-02T13:00:00.000Z ..... 等等 我该怎么做?我应该使用什么样的插件?

请您参考如下方法:

如果可能的话,我会推荐使用 pandas。

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

如果您需要字符串,请使用以下内容:

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