0

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?

sophros
  • 14,672
  • 11
  • 46
  • 75
kbr85
  • 1,416
  • 12
  • 27
  • 1
    Can you clarify why you expect the others *not* to work? Have you checked what they are parsed to? What is your criteria for "missing the initial 0"? Note that as per the docs: "When used with the strptime() method, the leading zero is optional for formats %d, %m, %H, %I, %M, %S, %J, %U, %W, and %V.". – MisterMiyagi Jan 19 '21 at 14:38
  • @MisterMiyagi If I use %Y%m%d I expect that a string like '101124' would raise an error since is missing the first '0'. Instead strptime returns datetime.datetime(1011, 2, 4, 13, 45, 23) for the second call in the example code given. – kbr85 Jan 19 '21 at 14:43
  • Does this answer your question? [How to require a timestamp to be zero-padded during validation in Python?](https://stackoverflow.com/questions/45595943/how-to-require-a-timestamp-to-be-zero-padded-during-validation-in-python) – MisterMiyagi Jan 19 '21 at 14:43
  • I don't see how that is a different problem. From the other question "[strptime] doesn't throw a ValueError exception as I would expect. Is there any way to enforce strptime to validate that it's zero-padded?". – MisterMiyagi Jan 19 '21 at 14:57
  • @MisterMiyagi You are right. In the question, the hour is not cero padded. The question is from 2017. If there is nothing new in these 3 years I will delete the question and write my own function. – kbr85 Jan 19 '21 at 15:02
  • You do not have to delete this question. We and you can vote it as a duplicate to act as a signpost for people with similar problems. – MisterMiyagi Jan 19 '21 at 15:03
  • @MisterMiyagi Ok. Leaving the question and going to write my own function. – kbr85 Jan 19 '21 at 15:08

1 Answers1

1

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.

sophros
  • 14,672
  • 11
  • 46
  • 75