Python中的四舍五入日期



假设我正在查看一个特定的日期:

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中有四舍五入日期的方法吗?

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

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

祝你好运!

相关内容

  • 没有找到相关文章

最新更新