Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rounding dates in Python

Say I am looking at a particular date:

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

How can I find:

  1. The date of the Monday right before my_date (if my_date isn't a Monday)
  2. The date of the closest Monday to my_date

Is there a way to round dates in datetime?

like image 579
Amelio Vazquez-Reina Avatar asked Mar 26 '14 15:03

Amelio Vazquez-Reina


2 Answers

you can use 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)

will output:

mydate is 2014-01-21
next monday is 2014-01-27
previous monday is 2014-01-20
Closest monday is 2014-01-20
like image 80
suhailvs Avatar answered Oct 28 '22 02:10

suhailvs


Use weekday:

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"

Output:

Today is  Monday  Wait  7  days for Monday
like image 34
venpa Avatar answered Oct 28 '22 03:10

venpa