2014-03-26 90 views
5

說我是在看一個特定日期:四捨五入日期

from datetime import date, timedelta 
days_to_substract = 65 
my_date = date.today()-timedelta(days=days_to_subtract) 

我如何才能找到:

  1. Mondaymy_date前右側的日期(如果my_date不是星期一)
  2. 最接近Mondaymy_date
日期

有沒有辦法將datetime中的日期倒圓?

回答

6

可以使用dateutil

from datetime import * 
from dateutil.relativedelta import * 

days_to_substract = 64 
my_date = (date.today()-timedelta(days=days_to_substract)) 
next=my_date+relativedelta(weekday=MO) 
previous=my_date+relativedelta(weekday=MO(-1)) 
print ('mydate is %s' %my_date) 
print ('next monday is %s' %next) 
print ('previous monday is %s' %previous) 

diff1=my_date-previous 
diff2=next-my_date 
if diff2<diff1: 
    print ('Closest monday is %s' %next) 
else: 
    print ('Closest monday is %s' %previous) 

將輸出:

mydate is 2014-01-21 
next monday is 2014-01-27 
previous monday is 2014-01-20 
Closest monday is 2014-01-20 
+0

說下一個星期一是否更準確,最接近的是那些絕對差異最小的兩個? – M4rtini

1

使用平日:

from datetime import date, timedelta 
d=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"] 
days_to_substract = 65 
my_date = (date.today()-timedelta(days=days_to_substract)) 
t=my_date.weekday() 
print "Today is ",d[t]," Wait ",(6-t+1)," days for Monday" 

輸出:

Today is Monday Wait 7 days for Monday 
+0

'6-t + 1'只是'7-t' :) –

+2

它有助於在週一到週日閱讀..0到6 ...很抱歉,如果它困擾你.... – user3

1

您可以使用date.weekday(http://docs.python.org/2/library/datetime.html#datetime.date.weekday)查找「my_date」的weekday整數值。然後,您可以使用當前工作日的差異(例如星期三的星期幾= 2)並執行另一個時間點計算。這對我工作時,我試過了:

from datetime import * 

days_to_subtract = 65 
my_date = (date.today() - timedelta(days=days_to_subtract)) 
dow = my_date.weekday() 
monday_my_date = (my_date - timedelta(days=dow)) 

print(monday_my_date) 

好運!