问题
I would have thought this question would already have an answer, but it doesn't seem to. In Python, I want to calculate the number of seconds from "now" to a specified time "today" or "tomorrow," whenever it next occurs (e.g., the next occurrence of 6:30 AM). The plan is to count down seconds and set off a musical alarm at the specified time. I'm pretty new at Python, and the datetime
documentation hasn't helped me with this so far. Can somebody give me some assistance with this?
回答1:
This should do the work:
from datetime import datetime, timedelta
now = datetime.now()
(timedelta(hours=24) - (now - now.replace(hour=6, minute=30, second=0, microsecond=0))).total_seconds() % (24 * 3600)
回答2:
In [12]: dt = datetime.datetime.now()
Out[13]: datetime.datetime(2016, 4, 23, 4, 8, 36, 742436)
In [14]: six_thirty = datetime.datetime(2016, 4, 23, 06, 30, 0, 0)
In [15]: six_thirty - dt
Out[15]: datetime.timedelta(0, 8483, 257564)
Notes
The datetime object is formatted in year, month, day, hour, min, second, millisecond.
The timedelta object gives the difference in days, seconds, microseconds, so for this example, there are 8483 seconds until 630 am, which translates to roughly 2 hrs and 21 minutes and 23 seconds.
回答3:
That's pretty sharp! And now for the whole thing, from the AM/PM time to the seconds remaining (there's probably a way to do this in fewer lines of code, but this works):
>>> from datetime import datetime, timedelta
>>> futime = '10:30 AM'
>>> fustrip = futime.rstrip(' AM')
>>> fusplit = fustrip.split(':')
>>> hr = int(fusplit[0])
>>> min = int(fusplit[1])
>>> now = datetime.now()
>>> secsleft = int((timedelta(hours=24) - (now - now.replace(hour=hr, minute=min, second=0, microsecond=0))).total_seconds() % (24 * 3600))
>>> secsleft
2063
That's where the time (10:30 AM) is today. For 6:30 tomorrow, it works too:
>>> hr = 6
>>> secsleft = int((timedelta(hours=24) - (now - now.replace(hour=hr, minute=min, second=0, microsecond=0))).total_seconds() % (24 * 3600))
>>> secsleft
74063
来源:https://stackoverflow.com/questions/36810003/calculate-seconds-from-now-to-specified-time-today-or-tomorrow