Python - Time data not match format

前端 未结 4 946
深忆病人
深忆病人 2021-01-27 00:42

I have string time in the following format

2016-12-10T13:54:15.294

I am using the following method to format the time:

time.strptime(

相关标签:
4条回答
  • 2021-01-27 01:03

    You need to first parse the string as its formatted, then print it out the way you want.

    >>> import datetime
    >>> ts = "2016-12-10T13:54:15.294"
    >>> parsed = datetime.datetime.strptime(ts, '%Y-%m-%dT%H:%M:%S.%f')
    >>> parsed
    datetime.datetime(2016, 12, 10, 13, 54, 15, 294000)
    >>> parsed.strftime('%b %d %H:%M:%S %Y')
    'Dec 10 13:54:15 2016'
    
    0 讨论(0)
  • 2021-01-27 01:05

    I think your date format is incorrectly specified in string. This should work:

    import datetime
    a = '2016-12-10T13:54:15.294'
    b= datetime.datetime.strptime(a,'%Y-%m-%dT%H:%M:%S.%f')
    print b
    
    0 讨论(0)
  • 2021-01-27 01:13

    Your format string is not correct.

    You can check format string just using strftime method of date object. For example:

    d = datetime.datetime.now()
    print(d.strftime('%Y-%d-%mT%H:%M:%S'))
    

    Output:

    Dec 16 11:02:46 2016
    

    But you have string in following format 2016-12-10T13:54:15.294, so you just need to change format string:

    print(time.strptime(ts, '%Y-%d-%mT%H:%M:%S.%f'))
    

    output:

    time.struct_time(tm_year=2016, tm_mon=10, tm_mday=12, tm_hour=13, tm_min=54, tm_sec=15, tm_wday=2, tm_yday=286, tm_isdst=-1)
    
    0 讨论(0)
  • 2021-01-27 01:30

    The error is not wrong, the format string is not even close to the string you're trying to parse.

    You have {year}-{month}-{day}T{hour}:{minute}:{second}.{milliseconds} but trying to parse it with {weekday name} {month name} {day} {hour}:{minute}:{second} {year}. Did you copy this from somewhere?

    According to the documentation, your format string should look more like %Y-%m-%dT%H:%M:%S.%f.

    >>> time.strptime('2016-12-10T13:54:15.294', '%Y-%m-%dT%H:%M:%S.%f')
    time.struct_time(tm_year=2016, tm_mon=12, tm_mday=10, tm_hour=13, tm_min=54, tm_sec=15, tm_wday=5, tm_yday=345, tm_isdst=-1)
    
    0 讨论(0)
提交回复
热议问题