views:

28

answers:

1

The scenario is as follows: given a totally arbitrary starting date in UTC there is an event that repeats every 24 hours. I need to calculate, given the current local time, how much time is left before the next event.

Ideally an ideal function would do:

time_since_start = now - start_time
remaining_seconds = time_remaining(time_since_start)

EDIT: Some clarifications. start_time defines the "epoch", the global start time since the event started repeating. Secondly, now is an arbitrary time occurring after start_time, local.

The issue is not calculating the occurrence of the next event (which would be simply adding 24 hours to start_time) but if I pick a time that falls between one event and the other, how much time is left before the next event.

I'd opt seconds as they can be quickly parsed into days, minutes and hours. Usage of datetime would be preferred (but not required) over other third-party modules as I am trying to reduce the number of dependencies.

I tried using datetime and timedelta, but the difference is always incorrect. What is the best way to proceed there?

A: 

What you want is start_time - now + (one day)

JoshD
It doesn't work if the two items are `datetime` items as they can't be subtracted to an int.
Einar
The problem with your setup is that your subtraction is wrong. If you want time until next event, you need to do `time of next event - now`. The time of the next event is one day + start_time.
JoshD
Something like: `seconds = (start_time - datetime.datetime.now() + datetime.timedelta(days=1)).seconds ; print '%d hours %d minutes %d seconds' % (seconds / 3600, (seconds / 60) % (seconds / 3600 * 60), seconds % 60)`
livibetter
Given the first answer I realized that my explanation was incorrect. I updated the question and I hope it's clearer now.
Einar
@Einar: My original answer pertains to your question. livibetter clarified it further. Please consider it.
JoshD