在使用Pandas时,我遇到了以下错误。我在StackOverflow上寻找其他解决方案,但他们没有解决我的错误。
代码:
import pandas as pd
df = pd.read_csv("my_csv_content_below.csv")
df["timestamp"] = pd.to_datetime(df["timestamp"])
df["timestamp"] = df["timestamp"].dt.tz_convert(timezone_for_plot)
错误:
Traceback (most recent call last):
File "<input>", line 1, in <module>
File ".../venv/lib/python3.6/site-packages/pandas/core/generic.py", line 5137, in __getattr__
return object.__getattribute__(self, name)
File ".../venv/lib/python3.6/site-packages/pandas/core/accessor.py", line 187, in __get__
accessor_obj = self._accessor(obj)
File ".../venv/lib/python3.6/site-packages/pandas/core/indexes/accessors.py", line 480, in __new__
raise AttributeError("Can only use .dt accessor with datetimelike values")
AttributeError: Can only use .dt accessor with datetimelike values
DataFrame:
>>> df["timestamp"]
0 2021-09-01 04:59:46+00:00
1 2021-09-01 04:59:46+00:00
2 2021-09-01 04:59:37+00:00
3 2021-09-01 04:59:37+00:00
4 2021-09-01 04:59:24+00:00
...
1418 2021-09-01 04:56:50-04:00
1419 2021-09-01 04:56:25-04:00
1420 2021-09-01 04:56:24-04:00
1421 2021-09-01 04:56:14-04:00
1422 2021-09-01 04:56:14-04:00
Name: timestamp, Length: 1423, dtype: object
数据类型:
>>> from datetime import datetime
>>> assert all([type(x) is datetime for x in df["timestamp"]])
True
可以从here下载存储为CSV的DataFrame。下面是一个示例,供将来参考:
,timestamp
0,2021-09-01 04:59:46+00:00
1,2021-09-01 04:59:46+00:00
2,2021-09-01 04:59:37+00:00
3,2021-09-01 04:59:37+00:00
4,2021-09-01 04:59:24+00:00
5,2021-09-01 04:59:24+00:00
6,2021-09-01 04:59:14+00:00
7,2021-09-01 04:59:14+00:00
8,2021-09-01 04:59:03+00:00
9,2021-09-01 04:59:03+00:00
...
发布于 2021-09-01 21:49:59
解决方案是按如下方式添加utc=True
:
import pandas as pd
df = pd.read_csv("my_csv_content_below.csv")
df["timestamp"] = pd.to_datetime(df["timestamp"], utc=True)
df["timestamp"] = df["timestamp"].dt.tz_convert(timezone_for_plot)
https://stackoverflow.com/questions/69020835
复制相似问题