Reputation: 96350
The following plot
import matplotlib
f= plt.figure(figsize=(12,4))
ax = f.add_subplot(111)
df.set_index('timestamp')['values'].plot(ax=ax)
ax.xaxis.set_major_locator(matplotlib.dates.HourLocator(interval=1))
ax.xaxis.set_major_formatter(matplotlib.dates.DateFormatter('%I'))
plt.show()
Renders the hour in the wrong zone (GMT) even though I have:
> df['timestamp'][0]
Timestamp('2014-09-02 18:37:00-0400', tz='US/Eastern')
As a matter of fact, if I comment out the line:
ax.xaxis.set_major_formatter(matplotlib.dates.DateFormatter('%I'))
the hour is rendered in the right time zone.
Why?
Upvotes: 12
Views: 6050
Reputation: 259
Using pytz
import pytz
import matplotlib.dates as mdates
my_tz = pytz.timezone('Europe/Berlin')
formatter = mdates.DateFormatter('%m-%d %H:%M', tz=my_tz)
Upvotes: 2
Reputation: 14239
If you don't want to change rcParams (which seems to be an easy fix), then you can pass the timezone to mdates.DateFormatter
.
from dateutil import tz
mdates.DateFormatter('%H:%M', tz=tz.gettz('Europe/Berlin'))
The problem is that mdates.DateFormatter
completely ignores everything you set in like plot_date
or xaxis_date
or whatever you use.
Upvotes: 10
Reputation: 5999
I think you can have the desired functionality by setting the timezone in rcParams
:
import matplotlib
matplotlib.rcParams['timezone'] = 'US/Eastern'
The formatter is timezone aware and will convert the timestamp to your rcParams timezone (which is probably at UTC), while if you don't format it, it will just take the timestamp and ignore the timezone. If I understand correctly.
More reading:
Upvotes: 20