无法使用 strptime 解析日期时间

Cannot parse datetime using strptime

我正在尝试从 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;DR:

您应该更改以下行:

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 时它会中断!

祝你好运:)