尝试在不带时间戳的Python中创建带有日期和时间的列表

时间:2018-09-01 01:34:36

标签: python pandas date datetime time

我正在尝试使用Astropy来确定日期/时间上的坐标。我想创建一个列表,其中包括按小时增加的日期和时间。例如:

[2018-01-01 00:00:00,2018-01-01 01:00:00,2018-01-01 02:00:00]

但是,我需要将日期设置为2018年1月1日至2019年8月31日,并包括0到24小时,即:

[2018-01-01 00:00:00,2018-01-01 01:00:00,2018-01-01 02:00:00,....2018-01-01 
23:00:00,2018-01-02 00:00:00,2018-01-02 01:00:00,2018-01-02 02:00:00,....
2018-01-02 23:00:00,...]

这是我到目前为止的代码:

import pandas as pd 
import numpy as np

dates=[]
for i in np.arange(0,24):
    d=pd.date_range('2018-01-01', periods=243) + pd.Timedelta(hours=i)
    dates.append(d)


tim=[]
for j,k in zip(np.arange(0,24),np.arange(0,243)):
    t=dates[j][k]
    tim.append(t)

print(tim)

返回:

[Timestamp('2018-01-01 00:00:00', freq='D'), Timestamp('2018-01-02 01:00:00', 
freq='D'), Timestamp('2018-01-03 02:00:00', freq='D'), Timestamp('2018-01-04 
03:00:00', freq='D'), Timestamp('2018-01-05 04:00:00', freq='D'), 
Timestamp('2018-01-06 05:00:00', freq='D'), Timestamp('2018-01-07 06:00:00', 
freq='D'), Timestamp('2018-01-08 07:00:00', freq='D'), Timestamp('2018-01-09 
08:00:00', freq='D'), Timestamp('2018-01-10 09:00:00', freq='D'), 
Timestamp('2018-01-11 10:00:00', freq='D'), Timestamp('2018-01-12 11:00:00', 
freq='D'), Timestamp('2018-01-13 12:00:00', freq='D'), Timestamp('2018-01-14 
13:00:00', freq='D'), Timestamp('2018-01-15 14:00:00', freq='D'), 
Timestamp('2018-01-16 15:00:00', freq='D'), Timestamp('2018-01-17 16:00:00', 
freq='D'), Timestamp('2018-01-18 17:00:00', freq='D'), Timestamp('2018-01-19 
18:00:00', freq='D'), Timestamp('2018-01-20 19:00:00', freq='D'), 
Timestamp('2018-01-21 20:00:00', freq='D'), Timestamp('2018-01-22 21:00:00', 
freq='D'), Timestamp('2018-01-23 22:00:00', freq='D'), Timestamp('2018-01-24 
23:00:00', freq='D')]

请帮助!谢谢。

2 个答案:

答案 0 :(得分:1)

很简单:

pd.date_range('2018-01-01', '2019-09-01', freq='H')

答案 1 :(得分:0)

要获取所需格式的列表,可以使用:

[str(ts) for ts in pd.date_range('2018-01-01', '2019-08-31', freq='H')]