python - 无法使用 strptime 解析日期时间

标签 python numpy 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;博士:

您应该更改以下行:

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/

相关文章:

python - numpy 中信号的 PSD 以及如何对其进行缩放

python - 提取多个 URL - Python

python - GeoDjango 图层映射和外键

python - 使用最小二乘法拟合权重衰减回归中的偏差

python - 我们如何在 python 中读取 16 个无符号整数 (16 uint) jpeg 文件

c - strptime() 读取相对于公元 1900 年的年份

r - 日期格式的冒号,介于秒和毫秒之间。如何解析R?

R,strptime(),%b,尝试将字符转换为日期格式

python - 在 Device Farm 上禁用自动关闭 iOS 警报

python - 此操作的正确语法是什么?