使用Strptime时的ValueError

时间:2018-02-03 15:53:33

标签: python strptime valueerror

我正在尝试从starttime中提取一周中的月,小时和星期几。

City: NYC
OrderedDict([('tripduration', '839'),
             ('starttime', '1/1/2016 00:09:55'),
             ('stoptime', '1/1/2016 00:23:54'),
             ('start station id', '532'),
             ('start station name', 'S 5 Pl & S 4 St'),
             ('start station latitude', '40.710451'),
             ('start station longitude', '-73.960876'),
             ('end station id', '401'),
             ('end station name', 'Allen St & Rivington St'),
             ('end station latitude', '40.72019576'),
             ('end station longitude', '-73.98997825'),
             ('bikeid', '17109'),
             ('usertype', 'Customer'),
             ('birth year', ''),
             ('gender', '0')])
datum_n_m = example_trips['NYC'][datetime.strptime('starttime','%m/%d/%Y %H:%M:%S')]
  

ValueError:时间数据' starttime'不符合格式'%m /%d /%Y%H:%M:%S'

1 个答案:

答案 0 :(得分:1)

首先,让我们制作一个[mcve]

# you do need to import stuff
from datetime import datetime

# the ordered dict is irrelevant, so get rid of it

# this reproduces the error
print (datetime.strptime('starttime','%m/%d/%Y %H:%M:%S'))

重现

  

builtins.ValueError:时间数据'starttime'与格式'%m /%d /%Y%H不匹配:%M:%S'

这是因为字符串“starttime”不是该格式的时间。这只是几封信。如果你已经做了一个基本的[mcve],你就可以解决自己的问题。基本调试:)

也许你的意思是:

start_time_as_string = example_trips['NYC']['starttime']
datum_n_m = datetime.strptime( start_time_as_string )