以Python显示基于当前日期的日期范围


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的一周">

有简单的方法吗?

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"

您可以只使用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

相关内容

  • 没有找到相关文章

最新更新