我目前正在学习字符串方法。但是,我遇到了这个问题,出现了 ValueError。
我有一个名为列表的列表,result_list
其中行的第一个索引是日期/时间戳,第二个索引是评论数。我被要求执行以下操作:
从日期中提取小时,这是该行的第一个元素。
使用该datetime.strptime()
方法解析日期并创建日期时间对象。
from datetime import datetime
# here is your list of values
result_list = ['8/16/2016 9:55', '6.0', '11/22/2015 13:43', '29.0']
# set the format
date_format = '%m/%d/%Y %H:%M'
for row in result_list:
time = row[0]
time_dt = datetime.strptime(time, date_format)
错误
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-6-ecf5afb3f99e> in <module>
9 for row in result_list:
10 time = row[0]
---> 11 time_dt = datetime.strptime(time, date_format)
e:\Anaconda3\lib\_strptime.py in _strptime_datetime(cls, data_string, format)
566 """Return a class cls instance based on the input string and the
567 format string."""
--> 568 tt, fraction, gmtoff_fraction = _strptime(data_string, format)
569 tzname, gmtoff = tt[-2:]
570 args = tt[:6] + (fraction,)
e:\Anaconda3\lib\_strptime.py in _strptime(data_string, format)
347 found = format_regex.match(data_string)
348 if not found:
--> 349 raise ValueError("time data %r does not match format %r" %
350 (data_string, format))
351 if len(data_string) != found.end():
ValueError: time data '8' does not match format '%m/%d/%Y %H:%M'
我假设我收到错误是由于datetime.strptime()构造函数期望值为 08 而不是 8。但是,我不确定从哪里开始解决此问题。
慕娘9325324
相关分类