在Python中舍入日期

时间:2014-03-26 15:55:29

标签: python datetime

说我正在查看特定日期:

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

我如何找到:

  1. Monday之前my_date的日期(如果my_date不是星期一)
  2. 最近的Mondaymy_date
  3. 的日期

    有没有办法在datetime中围绕日期?

3 个答案:

答案 0 :(得分:7)

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

答案 1 :(得分: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

答案 2 :(得分:1)

您可以使用date.weekday(http://docs.python.org/2/library/datetime.html#datetime.date.weekday)查找&#34; my_date&#34;的工作日整数值。然后你可以使用当前工作日的差异(例如星期三的工作日= 2)并执行另一个timedelta计算。当我尝试时,这对我有用:

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)

祝你好运!