Pav Sidhu
Pav Sidhu

Reputation: 6944

Getting the date of the first day of the week

I have records in a table which have a date field.

I would like to query the table so that the records returned are only the Sunday's date of a given week.

How could I use python's datetime library to achieve this? Thanks.

Upvotes: 15

Views: 25760

Answers (2)

Pav Sidhu
Pav Sidhu

Reputation: 6944

To get the beginning date of the week from Sunday:

datetime.today() - datetime.timedelta(days=datetime.today().isoweekday() % 7)

Upvotes: 32

Deep
Deep

Reputation: 1181

Thanks @PavSidhu and editors of that answer. Building further on that answer:

If your start of week is Sunday

import datetime
datetime.datetime.today() - datetime.timedelta(days=datetime.datetime.today().isoweekday() % 7)

If your start of week is Monday

import datetime
datetime.datetime.today()  - datetime.timedelta(days=datetime.datetime.today().weekday() % 7)

If you want to calculate start of week for a future date

import datetime
from dateutil.relativedelta import relativedelta

# 5 days ahead of today
future_date = datetime.datetime.today() + relativedelta(days=5)

# If Start of Week is Monday
print(future_date - datetime.timedelta(days=future_date.weekday() % 7))

# If start of week is Sunday
print(future_date - datetime.timedelta(days=future_date.isoweekday() % 7))

Diff: When start of week is Monday, we are using weekday() instead of isoweekday()

  • isoweekday() - Monday is 1 and Sunday is 7
  • weekday() - Monday is 0 and Sunday is 6

Upvotes: 31

Related Questions