Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

date

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.

like image 934
Ron Garrity Avatar asked Jan 27 '12 16:01

Ron Garrity


1 Answers

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)
like image 84
Cédric Julien Avatar answered Oct 11 '22 22:10

Cédric Julien