Python retrieves DayOfWeek as integer

I need the day of the week to be whole.

If I use the following for the day of the month mydate.day

, I would like to do the same for the weekday.

I tried mydate.weekday

it but it doesn't give me an integer (0 for Sunday to 6 for Saturday).

Any suggestions?

+3


source to share


3 answers


If you are using datetime.datetime

then use method datetime.datetime.weekday

:

>>> 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 (... + 1)% 7 because the method returns 0 for Monday, 6 for Sunday.



UPDATE

You can also use datetime.datetime.isoweekday

that return 1 for Monday, 7 for Sunday.

>>> d.isoweekday() % 7
1

      

+11


source


I am a little confused by your wording:

(0 for Sunday to 6 on Monday) # what is Monday 6?

But I'm wondering if you want isoweekday

:

>>> from datetime import datetime
>>> d = datetime.now()
>>> d.isoweekday()
1                                 # Monday

      



Edit

In light of your wish for Sunday to be 0, you should go with falsetru's answer (after editing):

>>> d.isoweekday() % 7

      

Or just convert Sunday to 0 elsewhere in your code.

+4


source


Python uses 0 for Monday. See the weekday documentation .

import datetime

now = datetime.datetime(2014, 11, 23)
print now
print now.weekday()

      

It's Sunday, so it prints this:

2014-11-23 00:00:00
6

      

This is an example for Monday:

import datetime

now = datetime.datetime.now()
print now
print now.weekday()

      

It's Monday, so it prints this:

2014-11-24 07:47:19.827000
0

      

+1


source







All Articles