Python, datetime "time span" in percent

Suppose I have these time variables:

start_time, end_time, current_time

I would like to know how much time is left in percent, checking current_timeand delta time between start_timeandend_time

IE: suppose the interval is 24 hours between start_time and end_time still between current_timeand end_time, there are 6 hours left until completion,% 25 should be left.

How can I do that?

+3
source share
3 answers

In Python 2.7.x, the total_seconds method is used for the delta time:

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 share temporary deltas directly (without passing total_seconds).

( Python 2.6.5: timedelta timedelta.)

+2

: , days, seconds microseconds. .

+3

Perhaps the 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
+1
source

Source: https://habr.com/ru/post/1737963/


All Articles