Question

import datetime

print datetime.datetime.now().strftime("Week of %m/%d") 
    #returns "Week of 04/18"

I want it to print "Week of 4/11 to 4/18" (with 4/13 being exactly one week beforehand) and it would need to account for if the week ended on 4/3, then it would be "Week of 3/27 to 4/3"

Is there an easy way to do this?

Was it helpful?

Solution

dateutil.relativedelta will do what you want:

import datetime
from dateutil.relativedelta import *

march27 = datetime.datetime(2014, 3, 27)
print (march27 + relativedelta(weeks=+1)).strftime("Week of %m/%d")
#prints "Week of 04/03"

OTHER TIPS

You could do it using only stdlib datetime module:

from datetime import date, timedelta

now = date(2014, 4, 18)
print now.strftime('Week of %m/%d')
# -> Week of 04/18
weekbefore = now - timedelta(days=7)
print "Week of {weekbefore:%m/%d} to {now:%m/%d}".format(**vars())
# -> Week of 04/11 to 04/18

It works the same if now = date(2014, 4, 3). It prints Week of 03/27 to 04/03 in this case.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top