Cannot parse the date in Python

前端 未结 3 856
挽巷
挽巷 2020-12-12 04:27

I need to parse date and time. Here is what I\'ve got:

import time
a = time.strptime(\'Apr 28 2013 23:01\', \"%b %d %y %H:%M\")
print a 

Bu

相关标签:
3条回答
  • 2020-12-12 05:02

    Jon's answer is of course correct, but as you noticed these things can be difficult to find.

    As a general suggestion for debugging strptime problems I recommend printing out a known datetime using the format string you use for parsing:

    from datetime import datetime
    
    d = datetime(2013, 4, 28, 23, 1)
    print d.strftime("%b %d %y %H:%M")
    print 'Apr 28 2013 23:01'
    

    A visual comparison of the output lines:

    Apr 28 13 23:01
    Apr 28 2013 23:01
    

    quickly finds the problem and also works when your format string is correct, but you are working with a different locale (e.g. in Spanish where it would expect 'Abr' instead of 'Apr')

    0 讨论(0)
  • 2020-12-12 05:07

    %y should be %Y for a 4 digit year...

    From the docs:

    %y  Year without century as a decimal number [00,99].    
    %Y  Year with century as a decimal number.
    
    0 讨论(0)
  • 2020-12-12 05:23

    You can

    import time
    a = time.strptime('Apr 28 2013 23:01', "%b %d %Y %H:%M")
    print time.strftime("%d/%m/%Y",a)
    

    with Y. It is followed by a conversion line of code, and gives result

    28/04/2013

    0 讨论(0)
提交回复
热议问题