Reputation: 3617
I need to get the day of the week as integer.
If i use the following for day of the month mydate.day
i would like to do the same for weekday.
i tried mydate.weekday
but this does not give me the integer (0 for sunday to 6 for saturday).
Any suggestions?
Upvotes: 3
Views: 2604
Reputation: 11591
I'm a little confused by your wording:
(0 for sunday to 6 for monday) # how would Monday be 6?
But I wonder if you want the isoweekday
:
>>> from datetime import datetime
>>> d = datetime.now()
>>> d.isoweekday()
1 # Monday
Edit:
In light of your desire for Sunday to be 0, you should go with falsetru's answer (after the edit):
>>> d.isoweekday() % 7
Or simply convert Sunday to 0 elsewhere in your code.
Upvotes: 4
Reputation: 368954
If you are using datetime.datetime
, use datetime.datetime.weekday
method:
>>> d = datetime.datetime.now()
>>> d
datetime.datetime(2014, 11, 24, 22, 47, 3, 80000)
>>> d.weekday() # Monday
0
>>> (d.weekday() + 1) % 7
1
You need to (... + 1) % 7 because the method return 0 for Monday, 6 for Sunday.
UPDATE
You can also use datetime.datetime.isoweekday
which return 1 for Monday, 7 for Sunday.
>>> d.isoweekday() % 7
1
Upvotes: 11
Reputation: 50540
Python uses 0 for Monday. See the weekday documentation.
import datetime
now = datetime.datetime(2014, 11, 23)
print now
print now.weekday()
This is a Sunday, so prints this:
2014-11-23 00:00:00
6
This is an example of a Monday:
import datetime
now = datetime.datetime.now()
print now
print now.weekday()
This is a Monday so prints this:
2014-11-24 07:47:19.827000
0
Upvotes: 1