【发布时间】:2017-10-11 20:37:46
【问题描述】:
如何正确设置 pyplot 以在给定时区绘制日期? 我可以看到放置 tzinfo 对象的各个地方,但所有这些要么什么都不做,要么不按预期远程工作。我从 csv 加载记录列表,每条记录都是 [UTC 中的原始时间戳,要绘制的数字]
import pytz
from datetime import datetime
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
estZone=pytz.timezone('US/Eastern')
records=[['10/10/17 12:00','100'],['11/10/17 12:00','150'],['12/10/17 12:00','200']]
def parseDT(stampString):
return datetime.strptime(stampString,'%d/%m/%y %H:%M')
def plotGraph():
xvalues=[]
yvalues=[]
for r in records:
rdatetime=(parseDT(r[0])) #parseDT just returns naive DT
rdatetime=pytz.utc.localize(rdatetime)
rdatetime=rdatetime.astimezone(tz=estZone)
xvalues.append(rdatetime)
yvalues.append(int(r[1]))
fig,ax=plt.subplots(figsize=(8,3))
plt.plot_date(xvalues,yvalues,ls='solid',lw=1.5,aa=True,marker='None',color='g')
dayFmt=mdates.DateFormatter('%a-%b-%d')
hrFmt=mdates.DateFormatter('%H:00')
ax.xaxis.set_major_formatter(dayFmt)
ax.xaxis.set_major_locator(mdates.DayLocator())
ax.xaxis.set_minor_locator(mdates.HourLocator(byhour=[6,12,18]))
ax.xaxis.set_minor_formatter(hrFmt)
plt.grid(b=True, which='both',linestyle='dotted')
plt.show()
plotGraph()
这会产生(减去一些格式)这个数字:
实际上仍然是UTC。如果我省略了astimezone(tz=estZone),它与结果相同,即使我已经验证了该部分确实可以正常工作。
如果我继续将tz=estZone 传递给plt.plot_date,则该数字是相同的。没有变化。如何更改此设置以根据我的 UTC 时间戳制作 EST 图?
【问题讨论】:
-
您可能希望提供该问题的minimal reproducible example。
-
抱歉,我不知道该添加什么内容会更清楚。代码块包含所有相关的内容,仅此而已。它正在绘制UTC。我希望它在 EST 中绘制时间。包括一些不起作用的例子。
-
驱动任何类型调试的主要引擎是可重复性。现在我无法重现上述问题,因为没有给出minimal reproducible example。 IE。我无法复制代码并运行它来查看问题。因此,我无法测试某些事情来定位问题,因此我无法帮助您。当然,您可能很幸运,发现编写包的人路过,从他的头顶上知道发生了什么,或者您可能会发现自己有太多时间编写这样的示例。但大多数时候,没有minimal reproducible example 的问题会被简单地关闭为题外话,或者永远不会得到回答。您的选择。
-
好了,现在可以独立运行了。
标签: python datetime matplotlib