首页 > 解决方案 > 'h' 是格式为 '%m/%d/%Y %h:%M' 的错误指令

问题描述

试图让它工作很长时间,不知道为什么它不会让我将字符串更改为日期时间,我是 Python 新手,请帮忙。

counts_by_hour = {}
comment_by_hour = {}


for row in result_list3:
    date = "10/15/2015 16:38"
    date2 = dt.datetime.strptime(date, "%m/%d/%Y %h:%M")

ValueErrorTraceback (most recent call last)
<ipython-input-19-98628a0af3bb> in <module>()
      4 for row in result_list3:
      5     date = "10/15/2015 16:38"
----> 6     date2 = dt.datetime.strptime(date, "%m/%d/%Y %h:%M")
      7 
      8 

/usr/lib/python3.4/_strptime.py in _strptime_datetime(cls, data_string, format)
    498     """Return a class cls instance based on the input string and the
    499     format string."""
--> 500     tt, fraction = _strptime(data_string, format)
    501     tzname, gmtoff = tt[-2:]
    502     args = tt[:6] + (fraction,)

/usr/lib/python3.4/_strptime.py in _strptime(data_string, format)
    327                 del err
    328                 raise ValueError("'%s' is a bad directive in format '%s'" %
--> 329                                     (bad_directive, format)) from None
    330             # IndexError only occurs when the format string is "%"
    331             except IndexError:

ValueError: 'h' is a bad directive in format '%m/%d/%Y %h:%M'```


标签: python

解决方案


%H使用了几个小时。因此,您的代码应如下所示:

date2 = dt.datetime.strptime(date, "%m/%d/%Y %H:%M")

推荐阅读