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?
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With