user257111
user257111

Reputation:

Python datetime.strptime month specifier doesn't seem to work

The month format specifier doesn't seem to work.

from datetime import datetime
endDate = datetime.strptime('10 3 2011', '%j %m %Y')
print endDate
2011-01-10 00:00:00 
endDate = datetime.strptime('21 5 1987', '%j %m %Y')
print endDate 
1987-01-21 00:00:00

Now, according to the manual the manual:

%m = Month as a decimal number [01,12].

So, what am I missing, other than the hair I've pulled out trying to understand why my django __filter queries return nothing (the dates going in aren't valid!)? I've tried 03 and 05 to no avail.

Versions of things, platform, architecture et al:

$ python --version
Python 2.7
$ python3 --version
Python 3.1.2
$ uname -r
2.6.35.11-83.fc14.x86_64 (that's Linux/Fedora 14/64-bit).

Upvotes: 3

Views: 1893

Answers (3)

Wooble
Wooble

Reputation: 89867

%j specifies a day of the year. It's impossible for the 10th day of the year, January 10, to occur in March, so your month specification is being ignored. Garbage In, Garbage Out.

Upvotes: 2

mouad
mouad

Reputation: 70021

You can't mix the %j with others format code like %m because if you look in the table that you linked %j is the Day of the year as a decimal number [001,366] so 10 correspondent to the 10 day of the year so it's 01 of January ...

So you have just to write :

>>> datetime.strptime('10 2011', '%j %Y')
datetime.datetime(2011, 1, 10, 0, 0)

Else if you you wanted to use 10 as the day of the mount you should do :

>>> datetime.strptime('10 3 2011', '%d %m %Y')
datetime.datetime(2011, 3, 10, 0, 0)

Upvotes: 6

samplebias
samplebias

Reputation: 37899

Isn't %j the "day of year" parser, which may be forcing strptime to choose January 21, overriding the %m rule?

Upvotes: 3

Related Questions