Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib ignoring timezone

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?

like image 205
Amelio Vazquez-Reina Avatar asked Sep 03 '14 23:09

Amelio Vazquez-Reina


People also ask

How does Python ignore time zones?

To remove timestamp, tzinfo has to be set None when calling replace() function. First, create a DateTime object with current time using datetime. now(). The DateTime object was then modified to contain the timezone information as well using the timezone.

Why is my plot in python empty?

The reason your plot is blank is that matplotlib didn't auto-adjust the axis according to the range of your patches. Usually, it will do the auto-adjust jobs with some main plot functions, such as plt. plot(), plt. scatter() ... .


2 Answers

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:

  • Matplotlib dates
  • A related answer
like image 70
Sebastian Avatar answered Nov 15 '22 19:11

Sebastian


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.

like image 41
Daniel F Avatar answered Nov 15 '22 20:11

Daniel F