Display a range of dates based on current date, in Python

天大地大妈咪最大 提交于 2019-12-13 04:39:53

问题


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?


回答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"



回答2:


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.



来源:https://stackoverflow.com/questions/23158450/display-a-range-of-dates-based-on-current-date-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!