Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Datetime, pandas, and timezone woes: AttributeError: 'datetime.timezone' object has no attribute '_utcoffset'

Here is a toy example of what I am trying to do:

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

When I run this, I get AttributeError: 'datetime.timezone' object has no attribute '_utcoffset'

What am I doing wrong?

like image 874
Sardathrion - against SE abuse Avatar asked Feb 22 '19 10:02

Sardathrion - against SE abuse


1 Answers

Mostly scraped this from @AndyHayden answer, but one option is to convert datetime.datetime to str and convert back to "timezone aware" timestamp using 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)

Returns:

enter image description here

like image 154
dubbbdan Avatar answered Nov 15 '22 10:11

dubbbdan