Skip to content Skip to sidebar Skip to footer

Python Weekday And Strftime("%u")

Is there a workaround for the following from datetime import datetime, timedelta a = datetime.now() # <== 2016-03-09 11:06:04.824047 print a.strftime('%U') >>> 10 #g

Solution 1:

%U treats weeks as starting on Sunday, not on Monday. From the documentation:

%U Week number of the year (Sunday as the first day of the week) as a zero padded decimal number. All days in a new year preceding the first Sunday are considered to be in week 0.

You could use the %W format, which gives a zero-padded week number based on Monday being the first day of the week:

%W Week number of the year (Monday as the first day of the week) as a decimal number. All days in a new year preceding the first Monday are considered to be in week 0.

The alternative is to use b.isocalendar()[1] if you need to get the week number as per ISO 8601. The rules for what is considered week 1 differ from the ISO calendar calculations; %W bases this on the first Monday in the year, while ISO 8601 states that the week that includes January 4 is the first week. For 2016 both systems align, but that's not the case in 2014, 2015 or 2019:

>>>d = datetime(2019, 3, 9)>>>d.strftime('%W')
'09'
>>>d.isocalendar()[1]
10

If you wait until Python 3.6, you can use the %V format to include the ISO week number, see issue 12006.

Post a Comment for "Python Weekday And Strftime("%u")"