Reputation: 462
I expected datetime.strftime
and datetime.strptime
calls to be reversible. Such that calling
datetime.strptime(datetime.now().strftime(fmt), fmt))
Would give the closest reconstruction of now()
(given the information preserved by the format).
However, this is not the case when formatting a date to a string with a YYYY-Week#
format:
>>> yyyy_u = datetime.datetime(1992, 5, 17).strftime('%Y-%U')
>>> print(yyyy_u)
'1992-20'
Formatting the string back to a date does not give the expected response:
>>> datetime.datetime.strptime(yyyy_u, '%Y-%U')
datetime.datetime(1992, 1, 1, 0, 0)
I would have expected the response to be the first day of week 20 in 1992 (17 May 1992).
Is this a failure of the %U
format option or more generally are datetime.strftime
and datetime.strptime
calls not meant to be reversible?
Upvotes: 1
Views: 86
Reputation: 728
From the Python docs regarding strptime()
behaviour:
- When used with the strptime() method, %U and %W are only used in calculations when the day of the week and the year are specified.
Day of the week must be specified along with Week number and Year.
(%Y-%U-%w)
datetime.datetime.strptime('1992-20-0', '%Y-%U-%w')
gives the first day of week 20 for 1992 year.
Upvotes: 1