gpt4 book ai didi

python - 如何使用 matplotlib 在 python 中绘制时间戳?

转载 作者:太空狗 更新时间:2023-10-30 02:10:00 25 4
gpt4 key购买 nike

我一直在整个谷歌上搜索这个,但看起来我无法准确找到我要找的东西。

所以,基本上,我有两个列表:一个列表包含时间戳数据,第二个列表包含与之对应的值。

现在我的问题是:我的时间戳采用以下格式

['Mon Sep 1 16:40:20 2015', 'Mon Sep 1 16:45:20 2015',
'Mon Sep 1 16:50:20 2015', 'Mon Sep 1 16:55:20 2015']

那么,matplotlib中使用的是哪种时间格式?我试图直接绘制它,但它给了我:

ValueError: invalid literal 

我可以使用datetime.datetime.strptime 来转换吗?如果不是,那么另一种方法是什么?

时间戳转换为正确的格式后,我应该如何绘制新转换的时间戳及其对应的值?

我可以使用 matplotlib.pyplot.plot(time, data) 还是必须使用 plot_date 方法来绘制它?

最佳答案

是的,使用 strptime

import datetime
import matplotlib.pyplot as plt

x = ['Mon Sep 1 16:40:20 2015', 'Mon Sep 1 16:45:20 2015',
'Mon Sep 1 16:50:20 2015', 'Mon Sep 1 16:55:20 2015']
y = range(4)

x = [datetime.datetime.strptime(elem, '%a %b %d %H:%M:%S %Y') for elem in x]

(fig, ax) = plt.subplots(1, 1)
ax.plot(x, y)
fig.show()

enter image description here

关于python - 如何使用 matplotlib 在 python 中绘制时间戳?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32728212/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com