How to calculate the time interval between two time strings

前端 未结 12 2634
生来不讨喜
生来不讨喜 2020-11-22 12:03

I have two times, a start and a stop time, in the format of 10:33:26 (HH:MM:SS). I need the difference between the two times. I\'ve been looking through documentation for

12条回答
  •  故里飘歌
    2020-11-22 12:50

    I like how this guy does it — https://amalgjose.com/2015/02/19/python-code-for-calculating-the-difference-between-two-time-stamps. Not sure if it has some cons.

    But looks neat for me :)

    from datetime import datetime
    from dateutil.relativedelta import relativedelta
    
    t_a = datetime.now()
    t_b = datetime.now()
    
    def diff(t_a, t_b):
        t_diff = relativedelta(t_b, t_a)  # later/end time comes first!
        return '{h}h {m}m {s}s'.format(h=t_diff.hours, m=t_diff.minutes, s=t_diff.seconds)
    

    Regarding to the question you still need to use datetime.strptime() as others said earlier.

提交回复
热议问题