Search code examples
pythonpython-3.xdatetimeparsingstrptime

Why does Python strptime skip missing 0s in a string when using %Y%m%d?


I am trying to use datetime.datetime.strptime to make sure a string has the format %Y%m%d-%H%M%S. However, strptime does not consider the 0 padded format in %Y or any other directive. For example, in the following code, only the last line raises an error. However, I would expect only the first strptime call to work.

from datetime import datetime

datetime.strptime('20101124-134523', '%Y%m%d-%H%M%S')

datetime.strptime(  '101124-134523', '%Y%m%d-%H%M%S')
datetime.strptime('20101124-34523', '%Y%m%d-%H%M%S')
datetime.strptime('20101124-3453', '%Y%m%d-%H%M%S')
datetime.strptime('20101124-343', '%Y%m%d-%H%M%S')

datetime.strptime(   '01124-134523', '%Y%m%d-%H%M%S')

Is this the expected behavior? Is there a way to make strptime to raise an error when the string is missing the initial 0s in one of the directives?


Solution

  • strptime is a relatively simple way to parse dates and time. I don't think it is possible to make it parse your examples in a way consistent with your examples.

    However, you may find some more powerful libraries be able to parse at least some of the examples you give. I suggest that you have a look at: dateparser or dateutil.