python读取csv画图datetime_如何从csv文件中读取日期/时间字段并在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.

解决方案

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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值