How to calculate next Friday?
Here is how you could do it using dateutil:
import datetime as DT
import dateutil.relativedelta as REL
today = DT.date.today()
print(today)
# 2012-01-10
rd = REL.relativedelta(days=1, weekday=REL.FR)
next_friday = today + rd
print(next_friday)
# 2012-01-13
(The days = 1
argument ensures that the "next Friday" is not the same as today
in case today
happens to be a Friday.)
To start off, you'll need the datetime
library:
import datetime
Then you need a starting date; that is, today.
d = datetime.date.today()
Starting from there, you'll want to keep going forward until you reach Friday. The date.weekday
method represents Monday through Sunday as 0 through 6, so:
while d.weekday() != 4:
If the current day isn't Friday, you'll have to add a day, one at a time. To add an interval of time to a date
object, you use a timedelta
object.
d += datetime.timedelta(1)
Put it all together, and d
will ultimately contain a date
object representing next Friday. Note that if today is Friday, this code will produce today; you can tweak it if you need it to produce next Friday instead.
A certain improvement on @taymon`s answer:
today = datetime.date.today()
friday = today + datetime.timedelta( (4-today.weekday()) % 7 )
4 is Friday's weekday (0 based, counting from Monday).( (4-today.weekday()) % 7)
is the number of days till next friday (%
is always non-negative).
After seeing @ubuntu's answer, I should add two things:
1. I'm not sure if Friday=4 is universally true. Some people start their week on Sunday.
2. On Friday, this code returns the same day. To get the next, use (3-today.weekday())%7+1
. Just the old x%n
to ((x-1)%n)+1
conversion.