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.
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.