Creating a datetime object by only providing the month or only providing the day of the week

Viewed 172

Creating a datetime object in Python by only providing the month preserves the month information:

>>> import datetime
>>> datetime.datetime.strptime('Feb', '%b')
datetime.datetime(1900, 2, 1, 0, 0)
>>> datetime.datetime.strptime('Feb', '%b').strftime('%B')
'February'

Since no year or day is provided, Python uses the defaults 1900 and 01, respectively, resulting in datetime.datetime(1900, 2, 1, 0, 0).

However, if a day of the week is provided:

>>> datetime.datetime.strptime('Tue', '%a')
datetime.datetime(1900, 1, 1, 0, 0)
>>> datetime.datetime.strptime('Tue', '%a').strftime('%A')
'Monday'

I understand that 1900-01-01 was Monday, but why isn't Python creating an object datetime.datetime(1900, 1, 2, 0, 0) which was the first Tuesday after 1900-01-01, similar to what it does with February in the first example?

It seems like the initial information (i.e. that the day was Tuesday) is lost without any warning or error. Is there a fundamental difference between creating a datetime object by only providing the month and only providing the day of the week?

1 Answers

As per docs:

For the datetime.strptime() class method, the default value is 1900-01-01T00:00:00.000: any components not specified in the format string will be pulled from the default value.

And important part:

Similar to %U and %W, %V is only used in calculations when the day of the week and the ISO year (%G) are specified in a strptime() format string. Also note that %G and %Y are not interchangeable.

I guess %a falls under the same condition but isn't specified in the docs.

You could use %G (ISO 8601 year) with %V (ISO 8601 week) alongside with %a, then it should work:

>>> datetime.datetime.strptime('1900 01 Tue', '%G %V %a').strftime('%Y-%m-%d %a')
'1900-01-02 Tue'

>>> datetime.datetime.strptime('1900 02 Tue', '%G %V %a').strftime('%Y-%m-%d %a')
'1900-01-09 Tue'

I believe it's because this way you specify the needed week.

Related