Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Im importing records from a CSV file using python csv module .

The date/Time field expects the date to be in a specific format, but different spreadsheet programs default to different types of formats and I dont want the user to have to change their down format.I want to find a way to either detect the format the string is in, or only allow several specified formats.

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

like image 849
AnveshVarma Avatar asked Feb 25 '23 02:02

AnveshVarma


1 Answers

dateutil can parse date strings in a variety of formats, without you having to specify 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)

Once you've collected the dates and values into lists, you can plot them with plt.plot. For example:

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

Per Joe Kington's comment, a graph similar to the one above could 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()
like image 118
unutbu Avatar answered Feb 27 '23 16:02

unutbu