14

How would I write a statement that says:

If today is Monday, then run this function.

My thoughts are:

if datetime.now().day == Monday:
     run_report()

But I know this is not the right way to do it. How would I properly do this?

sgerbhctim
  • 3,420
  • 7
  • 38
  • 60
  • This is something you could easily work out yourself, by reading the documentation to see what `day` returns, or even trying it yourself in the shell. – Daniel Roseman Aug 24 '17 at 21:05
  • @Alexander in that case, you can edit the duplicate list yourself and add your findings (I did that for you). Maybe you're not aware of this relatively new SE feature (with that one you can remove my "unfit" link and leave yours) – Jean-François Fabre Aug 25 '17 at 14:13
  • @Alexander specially for you: https://meta.stackoverflow.com/questions/355666/what-should-i-do-if-i-feel-that-the-original-question-of-the-duplicate-isnt-the – Jean-François Fabre Aug 25 '17 at 14:55

3 Answers3

42

You can use date.weekday() like this:

from datetime import date

# If today is Monday (aka 0 of 6), then run the report
if date.today().weekday() == 0:
    run_report()
ettanany
  • 19,038
  • 9
  • 47
  • 63
13
import datetime as dt

dt.date.today().isoweekday() == 1  # 1 = Monday, 2 = Tues, etc.
Alexander
  • 105,104
  • 32
  • 201
  • 196
4

Both datetime.date and datetime.datetime objects have a today method that return respectively a Date and a Datetime object.

Which both have a weekday and isoweekday methods. weekday count from Monday = 0, while isoweekday count from Monday = 1:

from datetime import date, datetime
if date.today().weekday() == 0:
    # it is Monday
if datetime.today().isoweekday() == 1:
   # it is Monday

See documentation

lee-pai-long
  • 2,147
  • 17
  • 18