Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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: 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 ?

like image 250
Hellnar Avatar asked Jul 10 '26 12:07

Hellnar


2 Answers

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

like image 154
Hans Avatar answered Jul 13 '26 20:07

Hans


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.

like image 26
avpx Avatar answered Jul 13 '26 22:07

avpx



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!