How to generate a sequence of future datetimes in Python and determine nearest datetime from set
I need to generate four datetime objects in 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"
Then I need to find which of those is closest to the current date/time.
开发者_如何学运维I wish I could say I have some starting code, but I have no idea where to start on this one.
This should get you started. I have the current time being passed into the function as a datetime, so if the argument is in EST, this should just work.
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]
The result will be the objects, in order, starting with the "soonest" one, and so on.
This seems like it might be a homework question. Is this enough sample code to get you started? It's probably not the MOST efficient, but it'll work.
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
For a list of times, "t", you can use: t = [time(5,30), time(8,30), time(13,0), time(17,30)] now = datetime.now()
today = [x for x in t if datetime.combine(today, x) > now]
not_today = set(t) - set(today)
精彩评论