我需要在Python中生成四个日期时间对象:
"The next instance of 5:30AM EST"
"The next instance of 8:30AM EST"
"The next instance of 1:00PM EST"
"The next instance of 5:30PM EST"
然后我需要找到哪一个最接近当前日期/时间。
我希望我可以说我有一些起始代码,但我不知道从哪里开始。
答案 0 :(得分:1)
这应该让你开始。我将当前时间作为日期时间传递给函数,因此如果参数在EST中,那么这应该可以正常工作。
def find_next(cur_dt):
import datetime as dt
t = [dt.time(5,30), dt.time(8,30), dt.time(13,0), dt.time(17,30)]
cur_t = cur_dt.time()
cur_d = cur_dt.date()
for i in range(len(t)):
if t[i] > cur_t:
rt = [t[(j+i)%len(t)] for j in range(len(t))]
rd = [cur_d] * (len(t)-i) + [cur_d + dt.timedelta(days=1)]*i
return [dt.datetime.combine(rd[j],rt[j]) for j in range(len(rt))]
# everything happens tomorrow
return [dt.datetime.combine(cur_d + dt.timedelta(days=1), i) for i in t]
结果将是对象,从“最快”开始,依此类推。
答案 1 :(得分:0)
这似乎可能是一个家庭作业问题。这个足够的示例代码可以帮助您入门吗?它可能不是最有效的,但它会起作用。
from datetime import datetime, time, timedelta
now = datetime.now()
today = datetime.date(now)
tomorrow = today + timedelta(days=1)
time_a = time (4, 0)
today_a = datetime.combine(today, time_a)
tomorrow_a = datetime.combine(tomorrow, time_a)
if (today_a - now)>timedelta(0):
print "%s is in the future" % today_a
if (tomorrow_a - now)>timedelta(0):
print "%s is in the future" % tomorrow_a
对于时间列表“t”,您可以使用: t = [时间(5,30),时间(8,30),时间(13,0),时间(17,30)] now = datetime.now()
today = [x for x in t if datetime.combine(today, x) > now]
not_today = set(t) - set(today)