Search code examples
pythontimeiso8601

Calculate time difference between two times using ISO 8601


I have two times for example:

2020-04-06T15:00:07Z 2021-07-28T19:18:02+0000

I am wondering how I can get the desired output of 1 year ago or 2 hours ago

I tried converting the times to seconds then subtracting that and converting the time to the desired output but I just can't find the code in the documentation that allows for that.


Solution

  • It works:

    from dateutil.parser import parse
    from dateutil.relativedelta import relativedelta
    
    datetime_1 = parse('2020-04-06T15:00:07Z')
    datetime_2 = parse('2021-07-28T19:18:02+00:00')
    
    delta = relativedelta(datetime_2, datetime_1)
    
    print(f"{delta.years} year {delta.months} months {delta.days} days {delta.hours} hours {delta.hours} minutes ago")
    
    # 1 year 3 months 22 days 4 hours 4 minutes ago