2

I need to calculate the difference between 2 differently formatted ISO dates. For example, 2019-06-28T05:28:14Z and 2019-06-28T05:28:14-04:00. Most of the answers here focus on only one format or another, i.e Z-formatted.

Here is what I have attempted using this library iso8601:

import iso8601

date1 = iso8601.parse_date("2019-06-28T05:28:14-04:00")
date2 = iso8601.parse_date("2019-06-28T05:28:14Z")

difference = date2 - date1

>>> datetime.timedelta(days=-1, seconds=75600)

I have also tried to replace Z with -00:00 but the difference is the same:

date2 = iso8601.parse_date("2019-06-28T05:28:14Z".replace("Z", "-00:00")

If I understand this correctly, it should show a difference of 4 hours. How do I calculate the difference in hours/days between 2 different date formats?

I am using Python 3.8.1.

martineau
  • 119,623
  • 25
  • 170
  • 301
hydradon
  • 1,316
  • 1
  • 21
  • 52

2 Answers2

3

I have used Pandas module but I think is the same with iso8601. To have the right difference I had to specify the same timezone in parsing function, as it follows:

import pandas as pd
date1 = pd.to_datetime("2019-06-28T05:28:14-04:00",utc=True)
date2 = pd.to_datetime("2019-06-28T05:28:14Z",utc=True)

Then my difference is expressed in a Timedelta format:

difference = (date2 - date1)
print(difference)
>> Timedelta('-1 days +20:00:00')

A timedelta of -1 days and 20h means 4 hours, infact if I convert the total seconds in hours I obtain:

print(difference.total_seconds()//3600)
>> -4

I hope this could be of help.

TeArge
  • 108
  • 5
1

An alternative is using the metomi-isodatetime package. It's created by the Met Office, so it must be standards-compliant.

Also, the package has no other dependencies, so it's 'lightweight'.

from metomi.isodatetime.parsers import TimePointParser

date1_s = "2019-06-28T05:28:14Z"
date2_s = "2019-06-28T05:28:14-04:00"

date1 = TimePointParser().parse(date1_s)
print(date1)

date2 = TimePointParser().parse(date2_s)
print(date2)

datediff = date2 - date1
print(type(datediff))
print(datediff)
print(datediff.hours)
# 

Running the above will produce the following output:

2019-06-28T05:28:14Z
2019-06-28T05:28:14-04:00
<class 'metomi.isodatetime.data.Duration'>
PT4H
4
pepoluan
  • 6,132
  • 4
  • 46
  • 76