get the last sunday and saturday's date in python -
looking leverage datetime
date of beginning , end of previous week, sunday saturday.
so, if it's 8/12/13 today, want define function prints:
last sunday 8/4/2013 , last saturday 8/10/2013
how go writing this?
edit: okay, there seems question edge cases. saturdays, want same week, else, i'd calendar week preceding today
's date.
datetime.date.weekday returns 0
monday. need adjust that.
try following:
>>> import datetime >>> today = datetime.date.today() >>> today datetime.date(2013, 8, 13) >>> idx = (today.weekday() + 1) % 7 # mon = 0, sun = 6 -> sun = 0 .. sat = 6 >>> idx 2 >>> sun = today - datetime.timedelta(7+idx) >>> sat = today - datetime.timedelta(7+idx-6) >>> 'last sunday {:%m/%d/%y} , last saturday {:%m/%d/%y}'.format(sun, sat) 'last sunday 08/04/2013 , last saturday 08/10/2013'
if allowed use python-deteutil:
>>> import datetime >>> dateutil import relativedelta >>> today = datetime.datetime.now() >>> start = today - datetime.timedelta((today.weekday() + 1) % 7) >>> sat = start + relativedelta.relativedelta(weekday=relativedelta.sa(-1)) >>> sun = sat + relativedelta.relativedelta(weekday=relativedelta.su(-1)) >>> 'last sunday {:%m/%d/%y} , last saturday {:%m/%d/%y}'.format(sun, sat) 'last sunday 08/04/2013 , last saturday 08/10/2013'
Comments
Post a Comment