0

In Python, I retrieved a start time and end time using datetime.datetime.now(). I would like to round any microseconds to the nearest second and convert days into hours. The final displayed format of the time difference should be "hours:minutes:seconds". Thanks in advance for the help!

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
RyanTC
  • 11
  • 2
  • Subtracting two `datetime`s will give you a [`timedelta`](https://docs.python.org/2/library/datetime.html#timedelta-objects), it's pretty easy given the attributes on that object. – Mark Ransom Jan 19 '17 at 17:43

1 Answers1

0

There is no direct way to format a timedelta object as you wish, so you have to do the calculations by yourself:

    delta = end - start
    seconds = int(round(delta.total_seconds()))
    minutes, seconds = divmod(seconds, 60)
    hours, minutes = divmod(minutes, 60)
    print("{:d}:{:02d}:{:02d}".format(hours, minutes, seconds))
Daniel
  • 42,087
  • 4
  • 55
  • 81