在美国东部时间每周五每周五下午6点开始一个小项目,给予新的特殊奖励并重置游戏。
实施例: 每周五美国东部时间下午6点,特别优惠将重置并推出新的优惠。我想做的就是让我们说星期二,我想知道有多少天:小时:分钟:秒到美国东部时间星期五6点。
我现在的代码可以使用,但问题是我必须手动更新下周五的日期。
import datetime
today = datetime.datetime.today()
reset = datetime.datetime(2018, 3, 18, 18, 00, 00)
print(reset-today)
在18日之后,我必须手动输入下周五的日期,我该如何自动进行?
答案 0 :(得分:1)
可能不是最优雅的方式,但这应该有帮助..
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