Skip to content

Instantly share code, notes, and snippets.

@morion4000
Created October 10, 2012 15:33
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save morion4000/3866374 to your computer and use it in GitHub Desktop.
Save morion4000/3866374 to your computer and use it in GitHub Desktop.
Python countdown to date script
from datetime import datetime, time
def dateDiffInSeconds(date1, date2):
timedelta = date2 - date1
return timedelta.days * 24 * 3600 + timedelta.seconds
def daysHoursMinutesSecondsFromSeconds(seconds):
minutes, seconds = divmod(seconds, 60)
hours, minutes = divmod(minutes, 60)
days, hours = divmod(hours, 24)
return (days, hours, minutes, seconds)
leaving_date = datetime.strptime('2012-01-01 01:00:00', '%Y-%m-%d %H:%M:%S')
now = datetime.now()
print "%d days, %d hours, %d minutes, %d seconds" % daysHoursMinutesSecondsFromSeconds(dateDiffInSeconds(now, leaving_date))
@ykcab
Copy link

ykcab commented Feb 11, 2016

@morion4000, thanks for this tip, I am trying to enhance this code and make the countdown live till it ends to 0 day 00 min 00 sec,
if you have a tip on that please do share.
thank

@zulonas
Copy link

zulonas commented Mar 4, 2019

@morion4000, thanks for this tip, I am trying to enhance this code and make the countdown live till it ends to 0 day 00 min 00 sec,
if you have a tip on that please do share.
thank

Here you go

from datetime import datetime, time
from time import sleep

def dateDiffInSeconds(date1, date2):
  timedelta = date2 - date1
  return timedelta.days * 24 * 3600 + timedelta.seconds

def daysHoursMinutesSecondsFromSeconds(seconds):
	minutes, seconds = divmod(seconds, 60)
	hours, minutes = divmod(minutes, 60)
	days, hours = divmod(hours, 24)
	return (days, hours, minutes, seconds)

req = datetime.strptime('2019-03-08 10:00:30', '%Y-%m-%d %H:%M:%S')
now = datetime.now()

while req>now:
    print("%dd %dh %dm %ds" % daysHoursMinutesSecondsFromSeconds(dateDiffInSeconds(now, req)))
    sleep(1)
    now = datetime.now()

print("Done")

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment