How to parse non-zero paded datetime string with strptime when leading zero is optional? Thanks

103 Views Asked by At

I've been trying to parse a datetime string in a file names with datetime.datetime.strptime().

import datetime
datetime.datetime.strptime('2023110912', "%Y%m%d%H%M")
datetime.datetime.strptime('202311912', "%Y%m%d%I%M")
datetime.datetime.strptime('202311912', "%Y%m%d%H%M")

I've tried search online for answers. According this python documents link: https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior

in Notes No.9, it says:

When used with the strptime() method, the leading zero is optional for formats %d, %m, %H, %I, %M, %S, %j, %U, %W, and %V. Format %y does require a leading zero.

I'm expecting to get the result:
datetime.datetime(2023, 1, 1, 9, 12)

But, instead, I got:
datetime.datetime(2023, 11, 9, 1, 2)

if '%m, %H, %I, %M, %S' are leading zero optional, how to distinguish above two date-time?

my python version: 3.10.7 (tags/v3.10.7:6cc6b13, Sep 5 2022, 14:08:36) [MSC v.1933 64 bit (AMD64)]

Did I miss something in the document? Can anybody help? Thanks a lot!

0

There are 0 best solutions below