Amelio Vazquez-Reina
Amelio Vazquez-Reina

Reputation: 96264

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?

Upvotes: 7

Views: 2718

Answers (3)

suhailvs
suhailvs

Reputation: 21680

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

Upvotes: 9

cymorg
cymorg

Reputation: 11

You could use date.weekday (http://docs.python.org/2/library/datetime.html#datetime.date.weekday) to find the weekday integer value for "my_date". Then you could use the difference of the current weekday (ex. weekday = 2 for wednesday) and perform another timedelta calculation. This worked for me when I tried it:

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)

Good Luck!

Upvotes: 1

venpa
venpa

Reputation: 4318

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

Upvotes: 1

Related Questions