Jazzin
Jazzin

Reputation: 55

Why are format codes "%-m" and "%-d" not working when parsing dates using the datetime module?

my_dates = [['y', 'd', 't', 'd', '2/1/2021', ''],
            ['v', 'd', 't', 't', '7/2/2020', ''],
            ['v', 'd', 't', 't', '10/1/2020', ''],
            ['d', 't', 't', 't', '12/1/2023', '']]

my_dates.sort(key=lambda date: datetime.strptime(date[4], "%-m/%-d/%y"))
print(my_dates)

I am trying to sort the dates in my list of lists from oldest to newest using a lambda function.

I was reading the documentation here: https://www.programiz.com/python-programming/datetime/strptime. It stated

%-m Month as a decimal number. 1, 2, ..., 12

and

%m Month as a zero-padded decimal number. 01, 02, ..., 12

but I am getting this error:

  File "C:\Python\Python39\lib_strptime.py", line 341, in _strptime
    raise ValueError("'%s' is a bad directive in format '%s'" %
ValueError: '-' is a bad directive in format '%-m/%-d/%y'

Upvotes: 1

Views: 793

Answers (1)

mkrieger1
mkrieger1

Reputation: 23250

The information that is shown on the page you were reading is incorrect.

If you are in doubt, you should always refer to the official Python documentation at https://docs.python.org.

The documentation of the datetime module lists all the valid format codes for strptime.

In your case you need %m/%d/%Y:

%m Month as a zero-padded decimal number. (9)

%d Day of the month as a zero-padded decimal number. (9)

%Y Year with century as a decimal number.

Importantly, refer to the note (9) at the bottom of the page:

  1. When used with the strptime() method, the leading zero is optional for formats %d, %m, [...]

This means that %m is used to parse the month both from a zero-padded decimal number (01, 02, ..., 12) and from a non-zero-padded decimal number (1, 2, ..., 12).

Upvotes: 1

Related Questions