說我是在看一個特定日期:四捨五入日期
from datetime import date, timedelta
days_to_substract = 65
my_date = date.today()-timedelta(days=days_to_subtract)
我如何才能找到:
- 的
Monday
的my_date
前右側的日期(如果my_date
不是星期一) - 最接近
Monday
至my_date
有沒有辦法將datetime
中的日期倒圓?
說我是在看一個特定日期:四捨五入日期
from datetime import date, timedelta
days_to_substract = 65
my_date = date.today()-timedelta(days=days_to_subtract)
我如何才能找到:
Monday
的my_date
前右側的日期(如果my_date
不是星期一)Monday
至my_date
有沒有辦法將datetime
中的日期倒圓?
可以使用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
使用平日:
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
'6-t + 1'只是'7-t' :) –
它有助於在週一到週日閱讀..0到6 ...很抱歉,如果它困擾你.... – user3
您可以使用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)
好運!
說下一個星期一是否更準確,最接近的是那些絕對差異最小的兩個? – M4rtini