转换熊猫时间戳列表

问题描述 投票:1回答:1

在我的变量“ Datelist3”中,有一个熊猫时间戳列表,格式如下:

[Timestamp('2019-12-04 09:00:00+0100', tz='Europe/Rome'), Timestamp('2019-12-04 09:30:00+0100', tz='Europe/Rome'), ....]

我在将此列表转换为以下格式的日期时间字符串列表时遇到困难:

['2019-12-04 09:00:00', '2019-12-04 09:30:00', .....]

我做了这些测试:

Datelist3.to_datetime # -> error: 'list' object has no attribute 'to_datetime'
Datelist3.dt.to_datetime # -> error: 'list' object has no attribute 'dt'
Datelist3.to_pydatetime() # -> error: 'list' object has no attribute 'to_pydatetime()'
Datelist3.dt.to_pydatetime() # -> error: 'list' object has no attribute 'dt'

我通过以下语句进入了变量“ Datelist3”:

Datelist3 = quoteIntraPlot.index.tolist()

如果我将此说明更改为:

Datelist3 = quoteIntraPlot.index.strftime("%Y-%m-%d %H:%M:%S").tolist()

这正是我想要实现的目标。问题是在10次中,6-7次是可以的,而3-4次则给我一个错误:“'Index'对象没有'strftime'“。真奇怪我该如何解决这个问题?

python-3.x pandas datetime type-conversion timestamp-with-timezone
1个回答
1
投票

如果您的数据格式正确,则可以使用:

time_list = [Timestamp('2019-12-04 09:00:00+0100', tz='Europe/Rome'), Timestamp('2019-12-04 09:30:00+0100', tz='Europe/Rome'), ....]
str_list = [t.strftime("%Y-%m-%d %H:%M:%S") for t in time_list]

但是,如果您遇到与以前相同的错误,则意味着并非您的所有索引都是时间戳。在这种情况下,您需要先清除数据。

© www.soinside.com 2019 - 2024. All rights reserved.