title: Sleep till next 15 minute hourly interval (00:00, 00:15, 00:30, 00:45)
body: <p>I need my script to sleep till the next 15 minute hourly interval, e.g. on the hour, quarter past, half past, and quarter too.</p>
  
  <p>It will look something like this </p>
  
  <pre><code>While True:
      //do something
      sleepy_time = //calculate time to next interval
      time.sleep(sleepy_time)
  </code></pre>
  
  <p>You could write a series of if statements to check what the current minutes past the hour is then do ‘if current &lt; 15’ and ‘if current &lt; 30’ etc but that seems messy and inefficient. </p>
  
  <p>EDIT: Building on @martineau's answer this is the code I went with.</p>
  
  <pre><code>import datetime, time
  
  shouldRun = True
  if datetime.datetime.now().minute not in {0, 15, 30, 45}:
      shouldRun = False
  # Synchronize with the next quarter hour.
  while True:
      if shouldRun == False:
          current_time = datetime.datetime.now()
          seconds = 60 - current_time.second
          minutes = current_time.minute + 1
          snooze = ((15 - minutes%15) * 60) + seconds
          print('minutes:', minutes, 'seconds', seconds, ' sleep({}):'.format(snooze))
          localtime = time.asctime( time.localtime(time.time()))
          print("sleeping at " + localtime)
          time.sleep(snooze)  # Sleep until next quarter hour.
          shouldRun = True
      else:
          localtime = time.asctime( time.localtime(time.time()))
          print("STUFF HAPPENS AT " + localtime)
          shouldRun = False
  </code></pre>
  
  <p>The difference between his answer and this is that this run the else block only once per interval then if the minute is still on the 0, 15, 30, 45 interval calculates the extra seconds to add to the minutes to sleep till the next interval.</p>