[英]How can I convert det unix time values from txt file to date values using matplotlib?
I basically want to convert the unix time values I have in the first row of my text file named 'EKTE9' to date. 我基本上想将文本文件“ EKTE9”的第一行中的Unix时间值转换为日期。 I think using the datetime library is the way to go, but I don't know how to implement that in my code. 我认为使用datetime库是可行的方法,但是我不知道如何在我的代码中实现它。 Some answers would be appreciated. 一些答案将不胜感激。
import matplotlib.pyplot as plt
import csv
x = []
y = []
with open('EKTE9.txt','r') as csvfile:
plots = csv.reader(csvfile, delimiter=',')
for row in plots:
x.append(int(row[0]))
y.append(float(row[3]))
plt.plot(x,y, label='Temperatur')
plt.xlabel('Tid')
plt.ylabel('Temperatur')
plt.title('Grafen viser temperatur under forsøket\n')
plt.legend()
plt.show()
Here are some values from the EKTE9.txt file: 以下是EKTE9.txt文件中的一些值:
1554058225,0.80,2.90,13.60,27.20
1554058525,0.30,0.80,9.60,26.70
The values goes on for about 200 lines 值持续约200行
You would first create a datetime
object using datetime.fromtimestamp()
. 您首先要使用datetime.fromtimestamp()
创建一个datetime
对象。 This can then be converted to a matplotlib number using date2num()
. 然后可以使用date2num()
将其转换为matplotlib数字。 Finally, you should use a DateFormatter()
to help with displaying the x-axis. 最后,您应该使用DateFormatter()
帮助显示x轴。
import matplotlib
import matplotlib.pyplot as plt
from datetime import datetime
import csv
x = []
y = []
with open('EKTE9.txt', 'r', newline='') as csvfile:
plots = csv.reader(csvfile, delimiter=',')
for row in plots:
x.append(matplotlib.dates.date2num(datetime.fromtimestamp(int(row[0]))))
y.append(float(row[3]))
hfmt = matplotlib.dates.DateFormatter('%d\n%H:%M')
plt.plot(x,y, label='Temperatur')
plt.gca().xaxis.set_major_formatter(hfmt)
plt.xlabel('Tid')
plt.ylabel('Temperatur')
plt.title('Grafen viser temperatur under forsøket\n')
plt.legend()
plt.show()
This would then show your two values as follows: 然后,将显示您的两个值,如下所示:
That did the job. 做到了。 Thank you very much Martin Evans. 非常感谢Martin Evans。 Fina code: 国际泳联代码:
import matplotlib
import matplotlib.pyplot as plt
from datetime import datetime
import csv
x = []
y = []
with open('EKTE9.txt','r') as csvfile:
plots = csv.reader(csvfile, delimiter=',')
for row in plots:
x.append(matplotlib.dates.date2num(datetime.fromtimestamp(int(row[0]))))
y.append(float(row[3]))
hfmt = matplotlib.dates.DateFormatter('%d\n%H:%M')
plt.plot(x,y, label='Temperatur')
plt.gca().xaxis.set_major_formatter(hfmt)
plt.xlabel('Tid')
plt.ylabel('Temperatur')
plt.title('Grafen viser temperatur under forsøket\n')
plt.legend()
plt.show()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.