Python Datetime Strptime Error: '-' is a bad directive in format '%-m-%-d-%y %-H:%M:%S'

Question:

I know that there have been similar questions asked, but they seemed to have to do with the way datetime deals (or doesn’t deal) with timezones.

The setup is a little complicated, and probably not relevant to the problem, but I thought it was important to include the code as is, so a little background:

I’ve got a dictionary of arrays. Each of these arrays represents an “attempt” by the same person, but taking place at different times. Ultimately I’m going to be looking for the earliest of these dates. This may be a bit of a roundabout solution, but I’m converting all of the dates to datetime objects, finding the earliest and then just using that index to pull out the first attempt:

Here’s what the code looks like to setup that array of attempt datetimes:

for key in duplicates_set.keys():
    attempt_dates = [datetime.strptime(attempt['Attempt Date'], "%-m-%-d-%y %-H:%M:%S") for attempt in duplicates_set[key]]

Here’s the format of what one of the original date strings looks like:

12-5-2016 3:27:58 PM

What I’m getting back is:

ValueError: '-' is a bad directive in format '%-m-%d-%y %-H:%M:%S'

I assume that’s referring to the dashes placed before the ‘m’, ‘d’ and ‘H’ because they’re non-zero-padded decimals. Why is it telling me that?

Asked By: slearner

||

Answers:

%-* — to skip padding — is a GNU libc extension. It’s not part of POSIX strftime, and thus not guaranteed to be portable to systems where your time-formatting calls aren’t eventually backed by GNU’s strftime C library function.

The Python datetime module documentation explicitly specifies the format strings it supports, and this extension is not given. Thus, while this is supported in GNU date and GNU strftime(), it isn’t available in Python datetime.

Answered By: Charles Duffy

I had the same issue;
date: 1/9/21

according to:
https://strftime.org/ the correct format would’ve been "%-d/%-m/%y"
which gave the bad directive error.
"%d-/%m-/%y" didn’t work either.

Weirdly enough what worked was "%d/%m/%y".

Answered By: David Mendes
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.