-1

I have this code below:

interval_time=int(input('how many seconds each interval?'))
print(time.strftime("%H:%M"))
while time.strftime("%H:%M")!=str('19:45'):
    time.sleep(interval_time)
    winsound.PlaySound("SystemExit",winsound.SND_ALIAS)    
winsound.PlaySound("SystemEnter",winsound.SND_ALIAS)

The thing is, I know how to get current time. I want it to look something like:

while *script_first_ran_time*!=*script_first_ran_time+30minutes*

I know how to convert the minutes, but it keeps re-taking the current time and adding 30 minutes to it. How do I make the initial time.strf() remain constant?

Thanks a lot!

Tak
  • 23
  • 4

1 Answers1

0

You've decided to make this task harder by using string representation of times. As these strings have no concept of being dates, performing date-related operations on them is troublesome. As an alternative, you should use dedicated library designed to work with dates and times, namely datetime.

Boilerplate code would look like this:

from datetime import datetime, timedelta

thirty_minutes_later = datetime.now() + timedelta(minutes=30)
while datetime.now() < thirty_minutes_later:
    pass  # do something

Here, datetime.now returns special objects that represents current time. timedelta returns special objects that, when added or subtracted from datetime instance, returns another datetime, shifted in time according to timedelta's state.

Also, notice that I've changed your condition from not equal to bigger than - it'll stop processing even if you won't hit your time spot precisely (and with millisecond resolution, you'd have to be extremely lucky to hit that).

Łukasz Rogalski
  • 22,092
  • 8
  • 59
  • 93
  • First of all, thank you very much for answering! While this is a different approach, it's a teachable moment nonetheless. I was wondering, you said making this task harder. How can I use the time as integer? – Tak Aug 15 '16 at 18:49
  • You can reuse [this answer](http://stackoverflow.com/questions/5998245/get-current-time-in-milliseconds-in-python) to get current timestamp in numeric form. Still, I do not understand how operating on raw timestamps is easier than using datetime module. – Łukasz Rogalski Aug 15 '16 at 19:01
  • That was just out of curiosity, already learned one new thing today, why not another? Thank you very much! – Tak Aug 15 '16 at 19:13