【问题标题】:AttributeError: Can only use .dt accessor with datetimelike values but cells contain date timeAttributeError:只能将 .dt 访问器与 datetimelike 值一起使用,但单元格包含日期时间
【发布时间】:2021-09-01 21:38:16
【问题描述】:

我在使用 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

数据帧:

>>> 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

存储为 CSV 的 DataFrame 可以下载here。以下是供将来参考的示例:

,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
...

【问题讨论】:

  • 您分享的内容的格式字符串不正确。 format='%Y-%m-%d %H:%M:%S+%f' 将解决它不转换为 datetime64 的问题
  • 谢谢,对不起。我已经确定了问题和答案。

标签: python pandas date time


【解决方案1】:

解决方法是添加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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多