Python-pptx - 折线图 - y 轴(系列)的日期时间值

Python-pptx - Line Chart - Datetime values for y axis (series)

我想创建一个折线图,其中 x 轴(类别)为文本值,y 轴(系列)为日期时间值。我的目标是实现类似的目标:

我尝试了以下代码。执行结束没有错误,但是PowerPoint告诉我内容有问题要求修复文件...

from pptx import Presentation
from pptx.util import Inches
from pptx.chart.data import ChartData
from pptx.enum.chart import XL_CHART_TYPE
import datetime

prs = Presentation()
prs.slide_width = Inches(16)
prs.slide_height = Inches(9)

title_slide_layout = prs.slide_layouts[1]
slide = prs.slides.add_slide(title_slide_layout)
title = slide.shapes.title

title.text = "Chart Example!"

val = [datetime.date(2019, 1, 4), datetime.date(2019, 1, 10),
    datetime.date(2019, 1, 11), datetime.date(2019, 1, 14), datetime.date(2019, 1, 15)]
chart_data = ChartData()
chart_data.categories = ['Start', 'Equipment 1', 'Equipment 2', 'Equipment 3', 'End']
chart_data.add_series('Plan', val)

x, y, cx, cy = Inches(0.5), Inches(1.5), Inches(10), Inches(5)
chart = slide.shapes.add_chart(
    XL_CHART_TYPE.LINE, x, y, cx, cy, chart_data
).chart

chart.has_legend = True
chart.legend.include_in_layout = False

prs.save('test.pptx')

有什么解决办法?我认为解决方法可能是将数据时间值转换为数字,将它们绘制为数字并以某种方式更改 y 轴标签以将值显示为 date

我找到了一个很好的解决方案。解决我的问题的步骤:

  1. 将日期时间值转换为 'Excel' 数字格式
  2. 将可选参数'number_format'传递给函数add_series,即number_format='mm/dd/yyyy'

这里是代码:

def excel_date(date1):
    temp = datetime.datetime(1899, 12, 30)    # Note, not 31st Dec but 30th!
    delta = date1 - temp
    return float(delta.days) + (float(delta.seconds) / 86400)


def getdata():  # function retrieves data form db, text file, etc...
    pass 


def start(stepname_lst, plan_date_lst):
    prs = Presentation()
    prs.slide_width = Inches(16)
    prs.slide_height = Inches(9)

    title_slide_layout = prs.slide_layouts[1]
    slide = prs.slides.add_slide(title_slide_layout)
    title = slide.shapes.title

    title.text = "Chart Example!"
    
    chart_data = CategoryChartData()
    chart_data.categories = stepname_lst
    chart_data.add_series('Plan', plan_date_lst, number_format='mm/dd/yyyy')
    # chart_data.add_series('Actual', actual_lst, number_format='mm/dd/yyyy')

    x, y, cx, cy = Inches(0.5), Inches(1.5), Inches(10), Inches(5)
    chart = slide.shapes.add_chart(
        XL_CHART_TYPE.LINE, x, y, cx, cy, chart_data
    ).chart

    prs.save('test.pptx')


if __name__ == '__main__':
    data_lst = getdata()
    stepname_lst= []
    plan_date_lst = []

    for r in data_lst:
        stepname_lst.append(r[0])
        plan_date_lst.append(excel_date(r[1]))
    
    start(stepname_lst, plan_date_lst)