Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Weirdly enough, '#' is a bad directive in format '%#H:%M'

I’ve seen a lot of similar questions, and still I don’t seem to be able find out what the issue with my code is.
I’m running this:

from datetime import datetime
date_st = "17:00"
date = datetime.strptime(date_st, "%#H:%M")

And I get the error:

ValueError: '#' is a bad directive in format '%#H:%M'

I’m running Windows, that’s why I use %#H and not %-H. I tried %-H though and it doesn’t work as well.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

%#H is only a valid formatting code for formatting a string (strftime), not parsing it with strptime.

I think strptime is provided by Python itself because windows doesn’t have such a function, so theoretically support for #H/-H can be added. But since %H can already parse a single optional leading 0 for one-digit hours, there isn’t much need for it (and POSIX strptime doesn’t allow %-H).

You will have to do something else to parse it. In this case, something like:

date_no_leading_zeros = date_st.lstrip("0")
# To support strings like "00:17" for 17 minutes past midnight
if date_no_leading_zeros.startswith(":"):
    date_no_leading_zeros = "0" + date_no_leading_zeros
date = datetime.strptime(date_no_leading_zeros, "%H:%M")

would work. But in other cases, you might want to use a regex to parse the date.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading