pythonpython-3.xstrptime

saving datetime with milliseconds and time zone - python


I can't figure out the correct second argument of strptime for the following date format

a = datetime.strptime('2017-03-09 14:00:00.000000+0000', '%y-%m-%d %H:%M:%S.%f+%z')

The error I get is:

ValueError: time data '2017-03-09 14:00:00.000000+0000' does not match format '%y-%m-%d %H:%M:%S.%f+%z'

Could anyone help me out?


Solution

  • The correct format string is:

    %Y-%m-%d %H:%M:%S.%f%z
    

    You can figure this out more easily next time by using strftime() to write a datetime using a given format. For example, your original:

    datetime.datetime.now().astimezone(tz=None).strftime('%y-%m-%d %H:%M:%S.%f+%z')
    

    gives:

    17-03-13 22:53:50.010314++0800
    

    And from there it is fairly easy to see what's wrong.