2016-08-02 125 views
0

我正在使用matplotlib绘制从CSV文件导入的一些数据。这些文件的格式如下:Python日期时间在美国和英国日期格式之间切换

Date,Time,A,B 
25/07/2016,13:04:31,5,25550 
25/07/2016,13:05:01,0,25568 
.... 
01/08/2016,19:06:43,0,68425 

的日期格式,因为它们是在英国,即%d/%m/%Y。最终结果是有两个图:A如何随时间变化,以及B如何随时间变化。我正在从CSV导入数据,如下所示:

import matplotlib 
matplotlib.use('Agg') 
from matplotlib.mlab import csv2rec 
import matplotlib.pyplot as plt 
from datetime import datetime 
import sys 
... 

def analyze_log(file, y): 
    data = csv2rec(open(file, 'rb')) 

    fig = plt.figure() 

    date_vec = [datetime.strptime(str(x), '%Y-%m-%d').date() for x in data['date']] 
    print date_vec[0] 
    print date_vec[len(date_vec)-1] 

    time_vec = [datetime.strptime(str(x), '%Y-%m-%d %X').time() for x in data['time']] 
    print time_vec[0] 
    print time_vec[len(time_vec)-1] 

    datetime_vec = [datetime.combine(d, t) for d, t in zip(date_vec, time_vec)] 
    print datetime_vec[0] 
    print datetime_vec[len(datetime_vec)-1] 

    y_vec = data[y] 
    plt.plot(datetime_vec, y_vec) 

    ... 
    # formatters, axis headers, etc. 
    ... 
    return plt 

而且在8月1日之前一切正常。然而,从那以后,matplotlib试图将我的01/08/2016数据点绘制为2016-01-08(1月08日)!

我得到一个绘图错误,因为它试图绘制1至7月:

RuntimeError: RRuleLocator estimated to generate 4879 ticks from 2016-01-08 09:11:00+00:00 to 2016-07-29 16:22:34+00:00: 

超过Locator.MAXTICKS * 2(2000)

我在做什么错在这里?在上面的代码中的打印语句的结果是:

2016-07-25 
2016-01-08 #!!!! 
13:04:31 
19:06:43 
2016-07-25 13:04:31 
2016-01-08 19:06:43 #!!!! 
+0

你在'strptime'使用''%Y-%间%D''..:该函数有两个选项来影响解析,dayfirst应该帮助吗? – Phillip

+0

@Phillip当我在格式中输入'%d /%m /%Y'时,出现错误:'ValueError:time data'2016-07-25'与格式'%d /%m /%Y'不匹配' ' – Frangipanes

+0

@Frangipanes:你的输入是使用混合格式吗? –

回答

0

你在%d/%m/%Y格式使用字符串,但你给的格式说明为%Y-%m-%d

+0

当我在格式中输入'%d /%m /%Y'时出现错误:'ValueError:time data'2016-07-25'与格式'%d /%m /%Y''不匹配 – Frangipanes

+0

'2016-07-25'未显示在您输入的内容或您已显示的代码中。那个错误发生在哪里? –

+0

当我更改'date_vec = [datetime.strptime(str(x),'%Y-%m-%d')。date()for data ['date']]''date_vec = [datetime。 strptime(str(x),'%d /%m /%Y')。date()for data ['date']]''。我也不明白,但是Python告诉我,当原始CSV具有'/'时,它读取的数据具有'-'。日期和时间字段的'dtype'都是'0'。 – Frangipanes

相关问题