字典中经过的时间 + datetime.timedelta

Elapsed time + datetime.timedelta in dictionary

您好,感谢您的帮助:)

问题

我的问题是,为什么 task.print_times() 会正确打印经过的时间...

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

但是 task.dict_times() 打印这个...

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

代码

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

打印字典时,根据 __repr__ 方法返回的值打印其中的单个 keys/elements。当您直接打印对象时,将调用 __str__ 方法。

考虑这个简单的例子:

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很好地解释了str/__str__repr/__repr__之间的区别。