0
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?

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
Nexion21
  • 149
  • 11

2 Answers2

1

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"
Dan
  • 2,766
  • 3
  • 27
  • 28
0

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.

jfs
  • 399,953
  • 195
  • 994
  • 1,670