Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: get last Monday of July 2010

How do I get the last Monday (or other day) of a given month?

like image 469
user984003 Avatar asked Dec 03 '22 01:12

user984003


2 Answers

Have a look at dateutil:

from datetime import datetime
from dateutil import relativedelta
datetime(2010,7,1) + relativedelta.relativedelta(day=31, weekday=relativedelta.MO(-1))

returns

datetime.datetime(2010, 7, 26, 0, 0)
like image 145
eumiro Avatar answered Dec 26 '22 21:12

eumiro


Using the calendar module from the stdlib:

import calendar
cal = calendar.Calendar(0)
month = cal.monthdatescalendar(2010, 7)
lastweek = month[-1]
monday = lastweek[0]
print(monday)

2010-07-26
like image 40
Gary van der Merwe Avatar answered Dec 26 '22 23:12

Gary van der Merwe