Home > Enterprise >  Elapsed time datetime.timedelta in dictionary
Elapsed time datetime.timedelta in dictionary

Time:02-25

Hello and thanks for your help :)

Question

My question is, why does task.print_times() prints the elapsed time correctly...

2022-02-24 21:35:23
2022-02-24 21:35:26
0:00:03

But task.dict_times() prints this...

{
  'time_start': '2022-02-24 21:35:23', 
  'time_end': '2022-02-24 21:35:26', 
  'time_elapsed': datetime.timedelta(seconds=3)
}

Code

from datetime import timedelta
from timeit import default_timer as timer
from time import strftime, localtime, sleep

class Timer:
  '''A utility class for capturing a task's processing time.
  '''
  def __init__(self):

    self.start_timer = None
    self.time_start = None
    self.stop_timer = None
    self.time_stop = None
    self.time_elapsed = None

  def start(self):
    '''Start the timer and capture the start time.
    '''
    self.start_timer = timer()
    self.time_start = strftime("%Y-%m-%d %H:%M:%S", localtime())

  def stop(self):
    '''Stop the timer and capture the stop time.
    '''
    self.stop_timer = timer()
    self.time_stop = strftime("%Y-%m-%d %H:%M:%S", localtime())

  def elapsed(self):
    '''Calculates the elapsed time.
    '''
    elapsed = timedelta(seconds=self.stop_timer-self.start_timer)
    self.time_elapsed = elapsed - timedelta(microseconds=elapsed.microseconds)

# --------------------------
# Example usage
# --------------------------
class Task:

  def __init__(self):

    self.task_timer = Timer()
    self.time_summary = {}

  def do(self):

    self.task_timer.start()
    sleep(3)
    self.task_timer.stop()
    self.task_timer.elapsed()

  def print_times(self):

    print(self.task_timer.time_start)
    print(self.task_timer.time_stop)
    print(self.task_timer.time_elapsed)

  def dict_times(self):

    self.time_summary['time_start'] = self.task_timer.time_start
    self.time_summary['time_end'] = self.task_timer.time_stop
    self.time_summary['time_elapsed'] = self.task_timer.time_elapsed
    print(self.time_summary)

task = Task()
task.do()
task.print_times()
task.dict_times()

CodePudding user response:

When you print a dictionary, the individual keys/elements within are printed according to the value returned by their __repr__ methods. When you print an object directly, the __str__ method is invoked instead.

Consider this simple example:

class Foo:
    def __str__(self):
        return 'foo'

    def __repr__(self):
        return 'bar'

x = Foo()
d = {'a': x}

print(x) # -> foo
print(d) # -> {'a': bar}

This question gives a good explanation of the difference between str/__str__ and repr/__repr__.

  • Related