Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.2k views
in Technique[技术] by (71.8m points)

datetime - How to plot timestamps in python using matplotlib?

I have been searching about this on entire google, but it looks like I am not able to find exactly what I am looking for.

So, basically, I have two lists: one list consists of timestamp data and a second list consists of values that correspond to that.

Now my issue is: my timestamps are in a following format

['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'] 

So, which time format is used in matplotlib? I tried to plot this straightaway but it gives me:

ValueError: invalid literal 

Can I use datetime.datetime.strptime to convert it? If not, then what is the other way of doing it?

After converting the timestamp in the proper format, how should I plot the new converted timestamp with it's corresponding value?

Can I use matplotlib.pyplot.plot(time, data) or do I have to use plot_date method to plot it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Yup, use 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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...