【问题标题】:Wrong datetime datetime.strptime('01/01/2017 00:03', '%m/%d/%Y %H:%M')错误的日期时间 datetime.strptime('01/01/2017 00:03', '%m/%d/%Y %H:%M')
【发布时间】:2020-07-01 00:14:03
【问题描述】:

我正在尝试将字符串转换为日期时间,但出现以下错误。

time_ = ad_status_df['updated_at'][2]
datetime.strptime(time_, '%Y/%m/%d %H:%M:%S')

output:
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-125-ad92608b3939> in <module>
----> 1 datetime.strptime(time_, '%Y/%m/%d %H:%M:%S')

~/opt/anaconda3/lib/python3.7/_strptime.py in _strptime_datetime(cls, data_string, format)
    575     """Return a class cls instance based on the input string and the
    576     format string."""
--> 577     tt, fraction, gmtoff_fraction = _strptime(data_string, format)
    578     tzname, gmtoff = tt[-2:]
    579     args = tt[:6] + (fraction,)

~/opt/anaconda3/lib/python3.7/_strptime.py in _strptime(data_string, format)
    357     if not found:
    358         raise ValueError("time data %r does not match format %r" %
--> 359                          (data_string, format))
    360     if len(data_string) != found.end():
    361         raise ValueError("unconverted data remains: %s" %

ValueError: time data '2020-06-30 03:00:04' does not match format '%Y/%m/%d %H:%M:%S'

我做错了什么?

【问题讨论】:

  • 嗨,我知道你是新来的。如果您认为某个答案解决了问题,请通过单击复选标记将其标记为“已接受”。谢谢!
  • 您提供的日期格式错误

标签: python string datetime


【解决方案1】:

答案就在错误信息中:

ValueError: time data '2020-06-30 03:00:04' does not match format '%Y/%m/%d %H:%M:%S'

这意味着time 的格式不是%Y/%m/%d %H:%M:%S

你可以:

  • 2020/06/30 03:00:04 格式提供时间,或者
  • strptime()的“格式”参数设置为'%Y-%m-%d %H:%M:%S'
time_ = ad_status_df['updated_at'][2]
datetime.strptime(time_, '%Y-%m-%d %H:%M:%S')

【讨论】:

  • 谢谢,工作正常,我忽略了字母 Y、m、d 并忘记了分隔符
  • 是的,发生这种情况...我很高兴能帮助你!
【解决方案2】:

正如错误所说,变量日期的格式为 %Y-%m-%d 您只需将 '/' 更改为 '-'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-26
    • 1970-01-01
    • 1970-01-01
    • 2022-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多