crld crld - 7 months ago 12
Python Question

Python Classes: update value of instance when it's called on

I'm playing around with classes, and have created one to time parts of my script.

import datetime


class Timer(object):

def __init__(self, *args, **kwargs):
self.StartTime = datetime.datetime.now()
self.TimeElapsed = self.timedif(datetime.datetime.now(), self.StartTime)

def hms_string(self, sec_elapsed):
h = int(sec_elapsed / (60 * 60))
m = int((sec_elapsed % (60 * 60)) / 60)
s = sec_elapsed % 60
return "{}:{:>02}:{:>05.2f}".format(h, m, s)

def timedif(self, end_datetime, start_datetime):
seconds_elapsed = (end_datetime - start_datetime).total_seconds()
return self.hms_string(seconds_elapsed)


What I would like for it to do is to print the amount of time that has elapsed since
StartTime
whenever
Timer.TimeElapsed
is instantiated. Of course, what it does is print
00:00:00
.

How can I modify my class so that when I call on
Timer.TimeElapsed
it uses the actual current time to compare to
StartTime
instead of the time the class was called?

Answer

you can use a method instead:

import datetime
import time

class Timer(object):
    def __init__(self, *args, **kwargs):
        self.StartTime = datetime.datetime.now()
        self.TimeElapsed = self.timedif(datetime.datetime.now(), self.StartTime)

    def hms_string(self, sec_elapsed):
        h = int(sec_elapsed / (60 * 60))
        m = int((sec_elapsed % (60 * 60)) / 60)
        s = sec_elapsed % 60
        return "{}:{:>02}:{:>05.2f}".format(h, m, s)

    def timedif(self, end_datetime, start_datetime):
        seconds_elapsed = (end_datetime - start_datetime).total_seconds()
        return self.hms_string(seconds_elapsed)

    def time_elapsed(self):
        return self.timedif(datetime.datetime.now(), self.StartTime)

t = Timer()
print "time elapsed from variable: {}".format(t.TimeElapsed)
time.sleep(1)
print "time elapsed from variable: {}".format(t.TimeElapsed)

t = Timer()
print "time elapsed from method: {}".format(t.time_elapsed())
time.sleep(1)
print "time elapsed from method: {}".format(t.time_elapsed())

output:

time elapsed from variable: 0:00:00.00
time elapsed from variable: 0:00:00.00
time elapsed from method: 0:00:00.00
time elapsed from method: 0:00:01.00
Comments