日期时间、熊猫和时区问题:AttributeError: 'datetime.timezone' object has no attribute '_utcoffset'

Sar*_*ica 6 timezone datetime matplotlib python-3.x pandas

这是我正在尝试做的一个玩具示例:

import pandas as pd
import datetime
import matplotlib
matplotlib.use('agg')  # noqa
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from time import sleep

lst = []
for x in range(0, 10):
    lst.append((datetime.datetime.now(datetime.timezone.utc), x))
    sleep(1)

df = pd.DataFrame(lst, columns=['Timestamp', 'Pressure'])
df.plot(kind='line', x='Timestamp', y='Pressure')
formatter = mdates.DateFormatter('%m/%d %T %Z', tz=df.index.tz)
plt.gca().xaxis.set_major_formatter(formatter)
plt.savefig('output.png')
Run Code Online (Sandbox Code Playgroud)

当我运行这个时,我得到 AttributeError: 'datetime.timezone' object has no attribute '_utcoffset'

我究竟做错了什么?

dub*_*dan 6

晴刮掉这从@AndyHayden答案,但一个方法是转换datetime.datetimestr使用和转换回“时区感知”时间戳pd.to_datetime

df = pd.DataFrame(lst, columns=['Timestamp', 'Pressure'])
df['Timestamp'] = pd.to_datetime(df.Timestamp.astype(str))
ax = df.plot(kind='line', x='Timestamp', y='Pressure')
plt.show()

df = df.set_index('Timestamp')

formatter = mdates.DateFormatter('%m/%d %T %Z', tz=df.index.tz)

ax.xaxis.set_major_formatter(formatter)
Run Code Online (Sandbox Code Playgroud)

返回:

在此处输入图片说明

  • 这个修复对我有用。门票 [#12310](https://github.com/matplotlib/matplotlib/issues/12310), [#22859](https://github.com/pandas-dev/pandas/issues/22859) 似乎捕获了问题,还没有解决。我计划在这些票证中添加信息,以提供更清晰的重现案例。 (2认同)