Ron Garrity
Ron Garrity

Reputation: 1463

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.

Upvotes: 5

Views: 2557

Answers (4)

Cédric Julien
Cédric Julien

Reputation: 80761

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)

Upvotes: 9

Shawn Chin
Shawn Chin

Reputation: 86864

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)

Upvotes: 0

Susam Pal
Susam Pal

Reputation: 34204

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

Upvotes: 3

AdamKG
AdamKG

Reputation: 14081

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)

Upvotes: 2

Related Questions