You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Matplotlib使用DateFormatter格式化x轴时间时始终返回00:00如何解决

问题原因

你传入prices_time参数是字符串类型,matplotlib绘制折线图时会默认将其处理为分类变量,x轴刻度的底层位置值对应0、1、2、3、4的整数序列。而mdates.DateFormatter仅能对matplotlib可识别的日期格式数值(从纪元开始计算的时间戳浮点数)生效,格式化整数0时会被默认识别为1970-01-01 00:00的时间戳,因此所有刻度最终都显示为00:00。

解决方法
  • 第一步:将时间字符串按照你定义的格式转换为datetime类型对象,匹配你输入的星期:时分格式,转换用的格式字符串为%A:%H:%M
  • 第二步:用转换后的datetime列表作为x轴参数绘图,mdates.DateFormatter即可正常识别时间数值并按规则格式化

修改后可正常运行的完整代码如下:

import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from datetime import datetime

def create_chart():
    stored_prices = [0.003197, 0.003197, 0.003197, 0.003197, 0.003197]
    prices_time = ['Thursday:09:00', 'Thursday:09:05', 'Thursday:09:10', 'Thursday:09:15', 'Thursday:09:20']
    # 新增:将字符串转换为datetime对象
    datetime_x = [datetime.strptime(t, "%A:%H:%M") for t in prices_time]

    fig, ax = plt.subplots()

    plt.tick_params(axis='y', which='both', labelleft=False, labelright=True)
    # 用转换后的datetime作为x轴数据
    plt.plot(datetime_x, stored_prices)
    plt.grid()
    plt.subplots_adjust(left=0.03, right=0.86)
    date_form = mdates.DateFormatter("%H:%M")
    ax.xaxis.set_major_formatter(date_form)
    # 如果需要同时显示星期,可将上一行修改为:date_form = mdates.DateFormatter("%A:%H:%M")
    print(stored_prices, prices_time)
    plt.show() #Preview of chart

create_chart()

内容的提问来源于stack exchange,提问作者Piotr F

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 18:45:03