How to read date / time field from csv file and plot graph in python

Import records from a CSV file using the python csv module.

The Date / Time field expects the date to be in a specific format, but different spreadsheet programs are used by default for different types of formats and I do not want the user to change their format down. I want to find a way to either determine the format in which the string is located, or allow several specified formats.

How to read a date / time field from a csv file and plot a graph accordingly.

+4
source share
1 answer

dateutil can analyze date strings in various formats without specifying in advance what format the date string is in

In [8]: import dateutil.parser as parser In [9]: parser.parse('Jan 1') Out[9]: datetime.datetime(2011, 1, 1, 0, 0) In [10]: parser.parse('1 Jan') Out[10]: datetime.datetime(2011, 1, 1, 0, 0) In [11]: parser.parse('1-Jan') Out[11]: datetime.datetime(2011, 1, 1, 0, 0) In [12]: parser.parse('Jan-1') Out[12]: datetime.datetime(2011, 1, 1, 0, 0) In [13]: parser.parse('Jan 2,1999') Out[13]: datetime.datetime(1999, 1, 2, 0, 0) In [14]: parser.parse('2 Jan 1999') Out[14]: datetime.datetime(1999, 1, 2, 0, 0) In [15]: parser.parse('1999-1-2') Out[15]: datetime.datetime(1999, 1, 2, 0, 0) In [16]: parser.parse('1999/1/2') Out[16]: datetime.datetime(1999, 1, 2, 0, 0) In [17]: parser.parse('2/1/1999') Out[17]: datetime.datetime(1999, 2, 1, 0, 0) In [18]: parser.parse("10-09-2003", dayfirst=True) Out[18]: datetime.datetime(2003, 9, 10, 0, 0) In [19]: parser.parse("10-09-03", yearfirst=True) Out[19]: datetime.datetime(2010, 9, 3, 0, 0) 

After you have collected the dates and values ​​in the lists, you can build them using plt.plot . For instance:

 import matplotlib.pyplot as plt import datetime as dt import numpy as np n=20 now=dt.datetime.now() dates=[now+dt.timedelta(days=i) for i in range(n)] values=[np.sin(np.pi*i/n) for i in range(n)] plt.plot(dates,values) plt.show() 

enter image description here

In a commentary on Joe Kington, a graph similar to the one above can also be made using matplotlib.dates.datestr2num instead of using dateutil.parser explicitly:

 import matplotlib.pyplot as plt import matplotlib.dates as md import datetime as dt import numpy as np n=20 dates=['2011-Feb-{i}'.format(i=i) for i in range(1,n)] dates=md.datestr2num(dates) values=[np.sin(np.pi*i/n) for i in range(1,n)] plt.plot_date(dates,values,linestyle='solid',marker='None') plt.show() 
+8
source

Source: https://habr.com/ru/post/1339650/


All Articles