Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 764
Pav Sidhu Avatar asked Sep 11 '16 23:09

Pav Sidhu


People also ask

What day is the first day of the week?

Monday is the first day of the week, according to the international standard for the representation of dates and times ISO 8601. However, in the United States and Canada, Sunday is considered to be the start of the week. This is because of religious reasons.

How do I find the first and last day of a week?

The day of the month for the first day of the week is equal to day of the month - day of the week . If you consider Monday to be the first day of the week, add 1 to the result. The day of the month for the last day of the week is equal to first day of the week + 6 .

How do I get the first day of the week in Python?

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.

Which day is the first day of the week in India?

According to the international standard ISO 8601, Monday is considered the first day of the week.


1 Answers

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
like image 109
Deep Avatar answered Sep 27 '22 15:09

Deep