In Python, showing the day of the week as an integer using datetime.strftime()
shows a different result than using datetime.weekday()
.
>>> import datetime
>>> now = datetime.datetime.now()
>>> now.strftime('%A')
'Sunday'
>>> now.strftime('%w') # Day of the week as an integer.
'0'
>>> now.weekday() # Day of the week as an integer, a different way.
6
With strftime()
, the string format %w
has Sunday as the first day of the week. With weekday()
, it's Monday instead.
What's the history of why these two are different?
The strftime() function is used to convert date and time objects to their string representation. It takes one or more input of formatted code and returns the string representation. Returns : It returns the string representation of the date or time object. List of format codes : Reference table for the format codes.
time – refers to time independent of the day (hour, minute, second, microsecond). datetime – combines date and time information. timedelta – represents the difference between two dates or times.
strptime is short for "parse time" where strftime is for "formatting time". That is, strptime is the opposite of strftime though they use, conveniently, the same formatting specification.
isoweekday() to get a weekday of a given date in Python Use the isoweekday() method to get the day of the week as an integer, where Monday is 1 and Sunday is 7. i.e., To start from the weekday number from 1, we can use isoweekday() in place of weekday() . The output is 1, which is equivalent to Monday as Monday is 1.
Originally, the ISO 8601 standard used 1 .. 7
to represent Monday through Sunday. For convenience, later on the interpretation 0=Sunday
was permitted.
If you want to use something that is more consistent, try using isoweekday
The 0=Monday
standard is the European convention. I guess that's no surprise :P
Python's strftime
function emulates that in the c library. Thus, the motivation that %w
returns 0
for a Sunday comes entirely from that.
In contrast, the method date.weekday()
returns a 6
for Sunday as it seeks to match the behaviour of the much older time
module. Within that module times are generally represented by a struct_time
and within this, struct_time.tm_day
uses a 6
to represent a Sunday.
The correct question then becomes ... why does time.struct_time
represent a Sunday as a 6
, when the C library's tm
struct uses a 0
??
And the answer is ... because it just does. This behaviour has existed ever since Guido first checked in gmtime
and localtime
functions in 1993.
And Guido cannot be wrong ... so you best ask him.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With