如何从csv文件中读取日期/时间字段并在python中相应地绘制图形 [英] How to read the date/time field from the csv file and plot a graph accordingly in python

查看:727
本文介绍了如何从csv文件中读取日期/时间字段并在python中相应地绘制图形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用python csv模块从CSV文件导入记录。

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.

如何从csv文件读取日期/时间字段并相应地绘制图形

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

推荐答案

dateutil 可以无需您事先指定日期字符串所处的格式:

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)

将日期和值收集到列表中后,您可以使用 plt.plot 绘制它们。例如:

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()

根据Joe Kington的评论,类似于上面的图也可以使用 matplotlib.dates.datestr2num 而不是使用 dateutil.parser 显式:

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()

这篇关于如何从csv文件中读取日期/时间字段并在python中相应地绘制图形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆