开发者

Python, datetime "time gap" percentage

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: Ass开发者_开发技巧ume 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 ?


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.)


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.


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜