import datetime
print datetime.datetime.now().strftime("Week of %m/%d")
#returns "Week of 04/18"
我想要它打印" 4/11周到4/18" (4/13正好提前一周) 并且它需要考虑周是否在4/3结束,然后它将是"周3/27到4/3"
有一种简单的方法吗?
答案 0 :(得分:1)
dateutil.relativedelta
会做你想做的事:
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"
答案 1 :(得分:0)
您只能使用stdlib datetime
模块:
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
如果now = date(2014, 4, 3)
,它的工作原理相同。在这种情况下,它会打印Week of 03/27 to 04/03
。