2014-04-18 177 views
0
import datetime 

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

我想它打印「周以4/18的4/11」(與4/13是事先正好一週) ,它需要如果一週結束於4月3日,那麼它將是「3/27至4/3周」顯示基於當前日期日期範圍,在Python

有沒有簡單的方法來做到這一點?

+0

你使用什麼編程語言?添加標籤,並在標題中提及。 –

+0

@BasilBourque謝謝,編輯帖子顯示語言 – Nexion21

回答

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