Path: csiph.com!optima2.xanadu-bbs.net!xanadu-bbs.net!feeder.erje.net!1.eu.feeder.erje.net!fu-berlin.de!uni-berlin.de!individual.net!not-for-mail From: Peter Pearson Newsgroups: comp.lang.python Subject: Re: Matplotlib X-axis timezone trouble [SOLVED] Date: 4 Jul 2015 17:37:07 GMT Lines: 52 Message-ID: References: X-Trace: individual.net 2+1QatqQXsLFuDwj5I5TkQIHDX9Q5v/KCIemeULj0d0XwD+xed Cancel-Lock: sha1:dJCNfGo+ANpA6nT3Lxq2NNGZ+60= User-Agent: slrn/pre1.0.0-18 (Linux) Xref: csiph.com comp.lang.python:93491 On Sat, 04 Jul 2015 07:29:45 +0300, Akira Li <4kir4.1i@gmail.com> wrote: > Peter Pearson writes: > >> The following code produces a plot with a line running from (9:30, 0) to >> (10:30, 1), not from (8:30, 0) to (9:30, 1) as I desire. >> >> If I use timezone None instead of pacific, the plot is as desired, but >> of course that doesn't solve the general problem of which this is a >> much-reduced example. >> >> If I use timezone US/Central, I get the same (bad) plot. >> >> import matplotlib.pyplot as plt >> import datetime >> import pytz >> pacific = pytz.timezone("US/Pacific") >> fig = plt.figure() >> plt.plot([datetime.datetime(2014, 10, 7, 8, 30, tzinfo=pacific), >> datetime.datetime(2014, 10, 7, 9, 30, tzinfo=pacific)], >> [0,1], marker="o", color="green") >> fig.autofmt_xdate() >> plt.show() >> >> Does anybody know why this shift is occurring? Is Matplotlib >> confused about what timezone to use in labeling the axis? How >> would I tell it what timezone to use (preferably explicitly in >> the code, not in matplotlibrc)? >> > > Your pytz usage is incorrect. > > Don't pass a pytz tzinfo object to the datetime construtor directly, use > `.localize()` method instead. Read the note at the very beginning of > pytz docs http://pytz.sourceforge.net/ Exactly. Thank you. For newcomers, the denouement of this thread is this: * Matplotlib had nothing to do with this problem, it was correctly displaying bad datetime.datetime values. * Python's datetime.datetime(..., tzinfo=timezone) is unreliable if timezone has daylight-saving time. * pytz's creators provide the localize() method specifically to remedy this problem. If you want to create a datetime object that has a timezone that might have daylight-saving time, use localize(). -- To email me, substitute nowhere->runbox, invalid->com.