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
?
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With