如何使用matplotlib绘制timedelta值

5

我想绘制一个与某些迭代值相关的持续时间(以秒为单位)图。我通过减去两个日期时间值来计算持续时间值。然后,我想使用现有工具以非常简单的方式绘制这些结果。

以下是我的代码,但它还没有起作用:

#!/usr/bin/env python

import datetime
import matplotlib.pyplot as plt
from numpy import arange

it = arange(10)
durations = [datetime.timedelta(hours=h+30) for h in it]

plt.plot(it, durations)

plt.show()

我收到了以下错误消息:
TypeError: float() argument must be a string or a number

我知道可以使用datetime而不是timedelta来使它起作用,但我的目标是绘制以小时为单位的持续时间(约40小时),所以渲染效果不佳。

1个回答

6
那是因为timedelta到float之间没有定义的转换方式。您可以使用:
durations = [datetime.timedelta(hours=h+30).total_seconds()/3600.0 for h in it]

将持续时间转换为浮点小时。如果您想在图表上使用漂亮的小时符号,请查看如何格式化您的刻度标签。您可以将小时(浮点数)转换为格式良好的小时字符串。
(编辑:将 .total_seconds 更改为 .total_seconds()

难道不应该是 timedelta.total_seconds() 吗?否则你最终只会得到一天内的持续时间余数。 - Deditos

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接