Pandas 图显示 UTC 而不是本地时区

问题描述 投票:0回答:1

使用以下代码并导入所有适当的库。这是我在生活日志中创建的每日日志帖子。

period = datetime.today().date() - timedelta(days=1)
archive = zipfile.ZipFile("/Users/steven/Downloads/export.zip", "r")
df = pd.read_xml(
    archive.open("apple_health_export/export.xml"),
    xpath="//Record",
    attrs_only=True,
    parse_dates=["creationDate", "startDate", "endDate"],
)
d1 = df[
    (df["endDate"].dt.date == period)
    & (df["type"] == "HKQuantityTypeIdentifierHeartRate")
]
d1["value"] = [pd.to_numeric(x) for x in d1["value"]]
plt.style.use("ggplot")
plt.rcParams["font.family"] = "PT Sans"
d1.sort_values(by="endDate").plot(
    x="endDate",
    y="value",
    xlabel="Time",
    ylabel="Heart Rate (BPM)",
    title="Heart Rate, Intraday",
).xaxis.set_major_formatter(mdates.DateFormatter("%-I:%M %p"))
plt.tight_layout()
plt.savefig(
    f"/Users/steven/Library/Mobile Documents/com~apple~CloudDocs/Web/gloriouslyawkwardlife.github.io/images/{period}-heartrateintraday.png",
    format="PNG",
)

问题在于,该图的 x 轴显示的是 UTC 时间,而不是 EDT (GMT-4),即使根据下面的示例传入的数据也使用 EDT。

785810  HKQuantityTypeIdentifierHeartRateVariabilitySDNN  Steven’s Apple Watch          11.1     ms  ... 2024-11-01 20:07:42-04:00 2024-11-01 20:08:42-04:00  67.3322  <<HKDevice: 0x30005b660>, name:Apple Watch, ma...
785811  HKQuantityTypeIdentifierHeartRateVariabilitySDNN  Steven’s Apple Watch          11.1     ms  ... 2024-11-01 22:06:15-04:00 2024-11-01 22:07:15-04:00  26.4656  <<HKDevice: 0x30005b660>, name:Apple Watch, ma...
785812  HKQuantityTypeIdentifierHeartRateVariabilitySDNN  Steven’s Apple Watch          11.1     ms  ... 2024-11-02 00:06:26-04:00 2024-11-02 00:07:25-04:00  197.345  <<HKDevice: 0x30005b660>, name:Apple Watch, ma...
785813  HKQuantityTypeIdentifierHeartRateVariabilitySDNN  Steven’s Apple Watch          11.1     ms  ... 2024-11-02 02:07:08-04:00 2024-11-02 02:08:07-04:00  69.5713  <<HKDevice: 0x30005b660>, name:Apple Watch, ma...
785814  HKQuantityTypeIdentifierHeartRateVariabilitySDNN  Steven’s Apple Watch          11.1     ms  ... 2024-11-02 04:06:10-04:00 2024-11-02 04:07:10-04:00  89.6994  <<HKDevice: 0x30005b660>, name:Apple Watch, ma...

完成的绘图显示错误时区的时间

我尝试按如下方式进行显式时区转换,但它不会影响最终结果:

df['endDate']=df['endDate'].dt.tz_convert(pytz.timezone('America/New_York'))

现在,如果我省略x轴格式(

.xaxis.set_major_formatter(mdates.DateFormatter("%-I:%M %p"))
),图表中显示的时间将显示在正确的时区中,但不是我喜欢的格式。 看到这张图片。

python pandas matplotlib timezone
1个回答
0
投票

您可以通过直接在格式中设置

mdates.DateFormatter
来将
tz
与正确的时区一起使用。

这是代码:

formatter = mdates.DateFormatter("%-I:%M %p", tz=pytz.timezone("America/New_York"))
ax = d1.sort_values(by="endDate").plot(
    x="endDate",
    y="value",
    xlabel="Time",
    ylabel="Heart Rate (BPM)",
    title="Heart Rate, Intraday",
)
ax.xaxis.set_major_formatter(formatter)

希望这对你有一点帮助。

© www.soinside.com 2019 - 2024. All rights reserved.