Reputation: 96264
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:
Monday
right before my_date
(if my_date
isn't a Monday)Monday
to my_date
Is there a way to round dates in datetime
?
Upvotes: 7
Views: 2718
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
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
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