How do I find the time difference between two datetime objects in python?

前端 未结 17 997
無奈伤痛
無奈伤痛 2020-11-22 11:06

How do I tell the time difference in minutes between two datetime objects?

17条回答
  •  感情败类
    2020-11-22 11:41

    I have used time differences for continuous integration tests to check and improve my functions. Here is simple code if somebody need it

    from datetime import datetime
    
    class TimeLogger:
        time_cursor = None
    
        def pin_time(self):
            global time_cursor
            time_cursor = datetime.now()
    
        def log(self, text=None) -> float:
            global time_cursor
    
            if not time_cursor:
                time_cursor = datetime.now()
    
            now = datetime.now()
            t_delta = now - time_cursor
    
            seconds = t_delta.total_seconds()
    
            result = str(now) + ' tl -----------> %.5f' % seconds
            if text:
                result += "   " + text
            print(result)
    
            self.pin_time()
    
            return seconds
    
    
    time_logger = TimeLogger()
    

    Using:

    from .tests_time_logger import time_logger
    class Tests(TestCase):
        def test_workflow(self):
        time_logger.pin_time()
    
        ... my functions here ...
    
        time_logger.log()
    
        ... other function(s) ...
    
        time_logger.log(text='Tests finished')
    

    and i have something like that in log output

    2019-12-20 17:19:23.635297 tl -----------> 0.00007
    2019-12-20 17:19:28.147656 tl -----------> 4.51234   Tests finished
    

提交回复
热议问题