Getting the date of the first day of the week - python

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.

To get the beginning date of the week from Sunday:
datetime.today() - datetime.timedelta(days=datetime.today().isoweekday() % 7)

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

Related

find previous sunday date based on today date in Django

Let us consider today date as 09/11/2021
And previous sunday date is 31/10/2021
today = datetime.date.today()
Now find previous sunday date
last_sunday = today - datetime.timedelta(days=today.weekday() + 8)
You can use relativedelta from dateutil.
from dateutil.relativedelta import relativedelta, SU
last_sunday = date.today() + relativedelta(weekday=SU(-2))

How to consider previous month first day and previous month last day in timestamp (13 digits--milliseconds) format in python 2.7 and python 3x?

Suppose today is August 28, 2019 i want timestamp of July 1,12:00:00 AM and July 31,23:59:59 PM. In general, I want the previous month date and time irrespective of year.
Alternatively with no additional modules:
from datetime import datetime, timedelta
now = datetime.now()
print(now)
firstOfThisMonth = now.replace(day=1)
print(firstOfThisMonth)
endOfLastMonth = firstOfThisMonth-timedelta(days=1)
print(endOfLastMonth)
firstOfLastMonth = endOfLastMonth.replace(day=1)
print(firstOfLastMonth)
print(firstOfLastMonth.replace(hour=0, minute=0, second=0, microsecond=0))
print(endOfLastMonth.replace(hour=23, minute=59, second=59, microsecond=0))
Outputs the following
2019-08-28 07:36:38.768223
2019-08-01 07:36:38.768223
2019-07-31 07:36:38.768223
2019-07-01 07:36:38.768223
2019-07-01 00:00:00
2019-07-31 23:59:59
The following should work for both Python 3x and Python2.7
from datetime import date
from dateutil.relativedelta import relativedelta
today = date.today()
d = today - relativedelta(months=1)
first_day = date(d.year, d.month, 1)
first_day.strftime('%A %d %B %Y')
#returns first date of the previous month - datetime.date(2019, 7, 1)
last_day = date(today.year, today.month, 1) - relativedelta(days=1)
last_day.strftime('%A %d %B %Y')
# returns the last date of the previous month - datetime.date(2019, 7, 31)
Note - The above code only returns the first and last date, not the time. I don't really understand why can't you just hard code the time in milliseconds since it will always be fixed, irrespective of the date.

Python - generate weekly date range from Saturday to Friday

I have a requirement to run a report on a weekly basis with week starting from Saturday and ending on Friday. However since the datetime or calendar module has week starting from Monday i couldn't use WEEKDAY option.
I tried the below option however it still gives me 5 for saturday,is there any options available to set weekstart day to Saturday so that for saturday it is 0 ? so that i can minus it from current date to get the desired dates or any other solution to acheive the same
Eg) If i run the report on August 30th it should fetch the data for August 18 to August 24
import calendar
calendar.setfirstweekday(calendar.SATURDAY)
calendar.firstweekday()
5
Thanks to the post Python: give start and end of week data from a given date slightly modified it based on my needs
dt = datetime.now()
start = (dt - timedelta(days = (dt.weekday() + 2) % 7)) - timedelta(days=7)
end = (start + timedelta(days=6))
print(start.strftime("%Y-%m-%d"))
print(end.strftime("%Y-%m-%d"))
It gives you 5 for Saturday, because 0 is Monday.
>>> calendar.setfirstweekday(calendar.MONDAY)
>>> calendar.firstweekday()
0

Print date of last Tuesday of each month of next year using Python

How can I print the date of the last Tuesday of each month for next year using Python.
For example the first line outputted would be: 30/Jan/2018
I do not want to have the full name of the month only the first 3 characters!
Currently I have figured out how to get the next year:
import datetime
now = datetime.datetime.now()
next_year = now.year + 1
Can anyone please help?
The calendar module is perfect for this:
You can use calendar.month_abbr which is an array of
abbreviated months just like you want.
week is an array representing the days of the week starting at Monday so Tuesday would be week[1].
import calendar
import datetime
now = datetime.datetime.now()
next_year = now.year + 1
for month in range(1, 13):
last_tuesday = max(week[1] for week in calendar.monthcalendar(next_year, month))
print('{}/{}/{}'.format(last_tuesday, calendar.month_abbr[month], next_year))
Output:
30/Jan/2018
27/Feb/2018
27/Mar/2018
24/Apr/2018
29/May/2018
26/Jun/2018
31/Jul/2018
28/Aug/2018
25/Sep/2018
30/Oct/2018
27/Nov/2018
25/Dec/2018
I would also suggest the pandas DateOffset object LastWeekOfMonth.
Describes monthly dates in last week of month like "the last Tuesday
of each month"
from pandas.tseries.offsets import LastWeekOfMonth
def last_tues(year):
return (pd.date_range('1/1/' + str(year), periods=12, freq='M')
- LastWeekOfMonth(n=1, weekday=1)).strftime('%d/%b/%Y'))
last_tues(2018)
Out[31]:
array(['30/Jan/2018', '27/Feb/2018', '27/Mar/2018', '24/Apr/2018',
'29/May/2018', '26/Jun/2018', '26/Jun/2018', '28/Aug/2018',
'25/Sep/2018', '30/Oct/2018', '27/Nov/2018', '25/Dec/2018'],
dtype='<U11')

Get Monday and Sunday and last year's Monday and Sunday, same week

Given datetime.datetime.now(), how do I get this week's Monday - Sunday and then the same Monday - Sunday for last year, considering leap years?
One idea I had was to get the timedelta for -365 days and then find the nearest Monday or Sunday. I'm sure there is a better way.
Edit: I don't mind using datetuil, if there is something in there that'd make this easier.
If using dateutil is not a problem, just use it :)
The relativedelta is the object you need
Here you will be able to substract one year to the current date.
from datetime import *
from dateutil.relativedelta import *
NOW = datetime.now()
last_monday = NOW+relativedelta(years=-1, weekday=MO)
last_sunday = NOW+relativedelta(years=-1, weekday=SU)
If this year's this Monday has date N, the same Monday last year would have a date N + 1 if there was no Feb 29 in between, otherwise last year's Monday would have a date N + 2.
from datetime import date, timedelta
today = date.today()
monday = today - timedelta(today.weekday())
sunday = monday + timedelta(6);
print monday, '-', sunday
monday_last_year = monday - timedelta(364) # We are trying to go to date N + 1.
if monday_last_year.weekday() == 1: # It will be either 0 or 1.
monday_last_year + timedelta(1) # This is date N + 2.
sunday_last_year = monday_last_year + timedelta(6)
print monday_last_year, '-', sunday_last_year
from datetime import date, timedelta
monday = date.today() - timedelta(days=date.today().weekday())
sunday = monday + timedelta(days=6)
The answer to the second question might depend on what counts as the 'same' monday-sunday. I'd start with the naive version and adjust if it it's not correct:
last_year_mon = monday - timedelta(weeks=52)
last_year_sun = last_year_mon + timedelta(days=6)
You can use .isocalendar() to retrieve the week number in the year, then from there derive the monday/sunday of that week for the current and previous year.
year, week, _ = datetime.datetime.now().isocalendar()
Then, using iso_to_gregorian from this answer:
this_sunday = iso_to_gregorian(year, week, 0)
this_monday = iso_to_gregorian(year, week, 1)
last_year_sunday = iso_to_gregorian(year - 1, week, 0)
last_year_monday = iso_to_gregorian(year - 1, week, 1)

Categories