【问题标题】:ValueError when using Strptime使用 Strptime 时出现 ValueError
【发布时间】:2018-02-03 15:53:33
【问题描述】:

我正在尝试从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' 不匹配

【问题讨论】:

    标签: python strptime valueerror


    【解决方案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 )
    

    【讨论】:

      猜你喜欢
      • 2011-10-06
      • 2015-01-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多