我正在尝试从 csv 加载数据并将其显示在 matplotlib 散点图中,其中在 X 轴上我格式化了日期时间。这是数据:
0,03/12/2017 21:00:00.000 +0000,4745
0,03/12/2017 22:00:00.000 +0000,3046
0,03/12/2017 23:00:00.000 +0000,2052
0,03/13/2017 00:00:00.000 +0000,1455
2,03/13/2017 00:00:00.000 +0000,2
1,03/13/2017 00:00:00.000 +0000,2
以及我使用的Python3.4代码:
import numpy as np
import matplotlib.pyplot as plt
import datetime as dt
retries, count = np.loadtxt(open('search-results.csv', 'r'),
delimiter=",",
skiprows=1,
unpack=True,
usecols=[0, 2])
time = np.loadtxt(open('search-results.csv', 'r'),
delimiter=",",
skiprows=1,
unpack=True,
usecols=[1],
dtype=str)
dates = [dt.datetime.strptime(str(d), "b'%d/%m/%Y %H:%M:%S.000 +0000'") for d in time]
plt.scatter(dates, retries, s=count)
plt.grid(which='both', color='#aaaaaa')
plt.savefig('out.png', format='png')
当我运行上面的代码时,看起来它正在解析数据,直到到达第 13 天:
ValueError: time data "b'03/13/2017 00:00:00.000 +0000'" does not match format "b'%d/%m/%Y %H:%M:%S.000 +0000'"
最佳答案
TL;博士:
您应该更改以下行:
dates = [dt.datetime.strptime(str(d), "b'%d/%m/%Y %H:%M:%S.000 +0000'") for d in time]
对此:
dates = [dt.datetime.strptime(str(d), "b'%m/%d/%Y %H:%M:%S.000 +0000'") for d in time]
<小时/>
您收到的错误是正确的,因为您告诉代码需要一个日期,格式为:"b'%d/%m/%Y %H:%M:%S.000 +0000'"
但您要向其传递一个格式如下的日期:
"b'%m/%d/%Y %H:%M:%S.000 +0000'" (interchanged month and date).
您的代码适用于前 3 行,因为 12 在一年的月份范围内,但是当它在第 4 行达到 13 时,它就会中断!
祝你好运:)
关于python - 无法使用 strptime 解析日期时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43318990/