4

I am trying to write a countdown clock script. I want to use a set date in the future and have it count down in a nice readable format. Hours, Min, Sec. I am going to print to a 16x2 lCD display. The problem I'm having is trying to take the output of the difference between dates into a nice format. I have attached what I have so far. I receive the error:

AttributeError: 'datetime.timedelta' object has no attribute 'strftime' 

This is my code:

from datetime import datetime
from time import strftime

deploy = datetime(2015, 3, 21, 0, 0)
mydate = datetime.now() - deploy
print (mydate.strftime("%b %d %H:%M:%S"))

I know how to print to my LCD and create a loop, just need help with this part.

fenceop
  • 1,439
  • 3
  • 18
  • 29
Bob Justison
  • 51
  • 1
  • 2
  • 3
    possible duplicate of [Python format timedelta to string](http://stackoverflow.com/questions/538666/python-format-timedelta-to-string) – ivan_pozdeev Feb 27 '15 at 22:32

1 Answers1

3

There are two issues:

  • the time difference may be incorrect if you use local time represented as a naive datetime object if the corresponding local times have different utc offsets e.g., around a DST transition
  • the difference is timedelta object that has no strftime() method

To fix it, convert deploy from local timezone to UTC:

#!/usr/bin/env python
import time
from datetime import datetime, timedelta

deploy = datetime(2015, 3, 21, 0, 0) # assume local time
timestamp = time.mktime(deploy.timetuple()) # may fail, see the link below
deploy_utc = datetime.utcfromtimestamp(timestamp)
elapsed = deploy_utc - datetime.utcnow() # `deploy` is in the future

where elapsed is the elapsed time not counting leap seconds (such as 2015-07-01 00:59:60 BST+0100).

More details on when time.mktime() may fail see at Find if 24 hrs have passed between datetimes - Python.

To convert timedelta to string, you could use str() function:

print(elapsed) # print full timedelta
# remove microseconds
trunc_micros = timedelta(days=elapsed.days, seconds=elapsed.seconds) 
print(trunc_micros) # -> 20 days, 13:44:14 <- 17 chars
# remove comma
print(str(trunc_micros).replace(',', '')) 
# -> 20 days 13:44:14 <- 16 chars

If you want a different format then convert to hours, minutes, second using divmod() function:

seconds = elapsed.days*86400 + elapsed.seconds # drop microseconds
minutes, seconds = divmod(seconds, 60)
hours, minutes = divmod(minutes, 60)
print("{hours:02d}:{minutes:02d}:{seconds:02d}".format(**vars()))
# -> 493:44:14
Community
  • 1
  • 1
jfs
  • 399,953
  • 195
  • 994
  • 1,670