Reputation: 13
Working on a small project where every Friday of everyweek at 6:00 PM EST a new special reward is given and reset for a game.
Example: Every Friday at 6:00 PM EST the special offer resets and comes out with a new one. What I want to do is let's say its Tuesday and I want to know how many Days:Hours:Minutes:Seconds are left until Friday 6:00 EST.
The code I have right now works but the issue is I have to manually update the date for the next friday.
import datetime
today = datetime.datetime.today()
reset = datetime.datetime(2018, 3, 18, 18, 00, 00)
print(reset-today)
After the 18th I would have to manually enter next fridays date, how could I do that automatically?
Upvotes: 0
Views: 332
Reputation: 2211
Probably not the most elegant way but this should help..
import datetime
#import relativedelta module, this will also take into account leap years for example..
from dateutil.relativedelta import relativedelta
#Create a friday object..starting from todays date
friday = datetime.datetime.now()
#Friday is day 4 in timedelta monday is 0 and sunday is 6. If friday is
#today it will stop at today..
#If it is friday already and past 18:00, add 7 days until the next friday.
if friday.hour > 18:
next_week = datetime.timedelta(7)
friday = friday - next_week
#else iterate though the days until you hit the first Friday.
else:
while friday.weekday() != 4:
friday += datetime.timedelta(1)
#the date will now be the first Friday it comes to, so replace the time.
friday = friday.replace(hour=18, minute=00, second=00)
#create a date for today at this time
date_now = datetime.datetime.now()
>>>2018-03-17 04:54:34.974214
# calculate using relativedelta
days_til_next_fri = relativedelta(friday, date_now)
print("The Time until next friday 18:00 is {} days {} hours {} minutes and {} seconds".format(days_til_next_fri.days, days_til_next_fri.hours, days_til_next_fri.minutes, days_til_next_fri.seconds))
>>>The Time until next friday 18:00 is 6 days 13 hours 50 minutes and 15 seconds
Upvotes: 1