如何使用datetim自动更改给定的日期和时间

2024-04-16 09:28:24 发布

您现在位置:Python中文网/ 问答频道 /正文

在一个小项目工作,每周五下午6:00美国东部时间一个新的特别奖励是给予和重置游戏。你知道吗

示例: 每周五美国东部时间下午6:00,特价商品将重置并推出新的特价商品。我想做的是假设今天是星期二,我想知道有多少人天:小时:分:秒是一直到周五东部时间6点。你知道吗

我现在的代码工作,但问题是我必须手动更新下周五的日期。你知道吗

import datetime
today = datetime.datetime.today()
reset = datetime.datetime(2018, 3, 18, 18, 00, 00)
print(reset-today)

18号以后我必须手动输入下周五的日期,我怎么能自动输入呢?你知道吗


Tags: 项目代码import游戏示例todaydatetime时间
1条回答
网友
1楼 · 发布于 2024-04-16 09:28:24

可能不是最优雅的方式,但这应该会有帮助。。你知道吗

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

相关问题 更多 >