3

Assume I have these datatime variables:

start_time, end_time, current_time

I would like to know how much time left as percentage by checking current_time and the time delta between start_time and the end_time

IE: Assume the interval is a 24 hours betwen start_time and end_time yet between current_time and end_time, there are 6 hours left to finish, %25 should be left.

How can this be done ?

Hellnar
  • 62,315
  • 79
  • 204
  • 279

3 Answers3

3

In Python 2.7.x, time delta has a method total_seconds to achieve this:

import datetime

startTime = datetime.datetime.now() - datetime.timedelta(hours=2)
endTime = datetime.datetime.now() + datetime.timedelta(hours=4)

rest = endTime - datetime.datetime.now()
total = endTime - startTime
print "left: {:.2%}".format(rest.total_seconds()/total.total_seconds())

In Python 3.2, you can apparently divide the time deltas directly (without going through total_seconds).

(This has also been noted in Python 2.6.5: Divide timedelta with timedelta.)

Community
  • 1
  • 1
Hans
  • 2,419
  • 2
  • 30
  • 37
3

Here's a hackish workaround: compute the total number of microseconds between the two values by using the days, seconds, and microseconds fields. Then divide by the total number of microseconds in the interval.

avpx
  • 1,892
  • 15
  • 13
1

Possibly simplest:

import time

def t(dt):
  return time.mktime(dt.timetuple())

def percent(start_time, end_time, current_time):
  total = t(end_time) - t(start_time)
  current = t(current_time) - t(start_time)
  return (100.0 * current) / total
Alex Martelli
  • 854,459
  • 170
  • 1,222
  • 1,395