将DatetimeIndex转换为datetime

时间:2018-10-17 11:20:47

标签: python pandas numpy dataframe matplotlib

如何将DatetimeIndex转换为datetime以在下一步中绘制数据?

我有一个DatetimeIndex列表,看起来像下面的例子

[<bound method DatetimeIndex.to_datetime of DatetimeIndex(['2016-07-04 16:19:35', '2016-07-04 16:19:35',
           '2016-07-04 16:19:35', '2016-07-04 16:19:34',
           '2016-07-04 16:19:34', '2016-07-04 16:19:34',
           '2016-07-04 16:19:33', '2016-07-04 16:19:33',
           '2016-07-04 16:19:32', '2016-07-04 16:19:32',
           ...
           '2016-07-30 02:59:38', '2016-07-31 03:09:07',
           '2016-07-31 03:09:03', '2016-07-31 03:09:03',
           '2016-07-31 03:09:55', '2016-07-31 03:09:54',
           '2016-07-31 03:09:54', '2016-07-31 02:59:39',
           '2016-07-31 02:59:38', '2016-07-31 02:59:38'],
          dtype='datetime64[ns]', name='event_timestamp', length=3981364, freq=None)>]

并且我需要这种格式

[datetime.datetime(2018, 10, 17, 13, 13, 39, 755816), datetime.datetime(2018, 10, 17, 13, 14, 39, 755816), datetime.datetime(2018, 10, 17, 13, 15, 39, 755816), datetime.datetime(2018, 10, 17, 13, 16, 39, 755816), datetime.datetime(2018, 10, 17, 13, 17, 39, 755816), datetime.datetime(2018, 10, 17, 13, 18, 39, 755816), datetime.datetime(2018, 10, 17, 13, 19, 39, 755816), datetime.datetime(2018, 10, 17, 13, 20, 39, 755816), datetime.datetime(2018, 10, 17, 13, 21, 39, 755816), datetime.datetime(2018, 10, 17, 13, 22, 39, 755816), datetime.datetime(2018, 10, 17, 13, 23, 39, 755816), datetime.datetime(2018, 10, 17, 13, 24, 39, 755816)]

我的Python代码类似于以下示例。

timeStamp = [data1[data1.columns[0]].index]
dateTime = []

for i in timeStamp:
    dateTime = i.to_datetime

希望您能帮助我,解决我的小问题。

1 个答案:

答案 0 :(得分:3)

matplotlib pandas 日期时间配合使用很好,但是如果确实需要将其转换为python日期时间,请使用DatetimeIndex.to_pydatetime

idx = pd.DatetimeIndex(['2016-07-04 16:19:35', '2016-07-04 16:19:35',
           '2016-07-04 16:19:35', '2016-07-04 16:19:34',
           '2016-07-04 16:19:34', '2016-07-04 16:19:34',
           '2016-07-04 16:19:33', '2016-07-04 16:19:33',
           '2016-07-04 16:19:32', '2016-07-04 16:19:32'])

print (idx)
DatetimeIndex(['2016-07-04 16:19:35', '2016-07-04 16:19:35',
               '2016-07-04 16:19:35', '2016-07-04 16:19:34',
               '2016-07-04 16:19:34', '2016-07-04 16:19:34',
               '2016-07-04 16:19:33', '2016-07-04 16:19:33',
               '2016-07-04 16:19:32', '2016-07-04 16:19:32'],
              dtype='datetime64[ns]', freq=None)

print (idx.to_pydatetime())
[datetime.datetime(2016, 7, 4, 16, 19, 35)
 datetime.datetime(2016, 7, 4, 16, 19, 35)
 datetime.datetime(2016, 7, 4, 16, 19, 35)
 datetime.datetime(2016, 7, 4, 16, 19, 34)
 datetime.datetime(2016, 7, 4, 16, 19, 34)
 datetime.datetime(2016, 7, 4, 16, 19, 34)
 datetime.datetime(2016, 7, 4, 16, 19, 33)
 datetime.datetime(2016, 7, 4, 16, 19, 33)
 datetime.datetime(2016, 7, 4, 16, 19, 32)
 datetime.datetime(2016, 7, 4, 16, 19, 32)]