Search code examples
pythondatetimeformatstrptimestrftime

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.


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.