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


Question

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.

1
4
2/14/2011 1:30:11 PM

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()
8
2/14/2011 5:57:08 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon