5

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.

Ron Garrity
  • 1,383
  • 2
  • 13
  • 25

4 Answers4

9

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)
mcard
  • 617
  • 1
  • 9
  • 16
Cédric Julien
  • 78,516
  • 15
  • 127
  • 132
3

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
Susam Pal
  • 32,765
  • 12
  • 81
  • 103
2
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)
AdamKG
  • 13,678
  • 3
  • 38
  • 46
0

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)
Community
  • 1
  • 1
Shawn Chin
  • 84,080
  • 19
  • 162
  • 191