Home > Software design >  Adding days to a ISO 8601 format date in Python
Adding days to a ISO 8601 format date in Python

Time:09-23

I need to add 3 hours to a date in iso 8601 format in python, for example "2022-09-21T22:31:59Z" due to time difference. In this time information that is returned to me from the API, I only need Y/M/D information, but due to the 3 hour difference, the day information needs to go one step further in the date information, as will be experienced in the date I conveyed in the example. How can I overcome this problem? I think the format of the date format is ISO 8601 but can you correct me if I am wrong?

ex. api response;

"createdDateTime": "2022-09-21T22:31:59Z"

what i need;

"createdDateTime": "2022-09-21T22:31:59Z" to "2022-09-22T01:31:59Z"

CodePudding user response:

Try this code it will definitely work:

from datetime import datetime,timedelta

parsed_date=datetime.strptime("2022-09-21T22:31:59Z", "%Y-%m-%dT%H:%M:%SZ")

Updated_date = parsed_date  timedelta(hours=3)

print(Updated_date)

CodePudding user response:

If you have a proper JSON string you can parse it with json, extract the string value, parse that with datetime.fromisoformat into a datetime value and then get the date from it :

import json
from datetime import datetime
data=json.loads('{"createdDateTime": "2022-09-21T22:31:59 00:00"}')
isostr=data['createdDateTime'].replace('Z',' 00:00')
fulldate=datetime.fromisoformat(isostr)
fulldate.date()
-----
datetime.date(2022, 9, 21)

The replacement is necessary because fromisoformat doesn't understand Z

Adding 3 hours to fulldate will return 1 AM in the next day:

fulldate   timedelta(hours=3)
------
datetime.datetime(2022, 9, 22, 1, 31, 59, tzinfo=datetime.timezone.utc)

fulldate is in UTC. It can be converted to another timezone offset using astimezone

fulldate.astimezone(tz=timezone(timedelta(hours=3)))
---
datetime.datetime(2022, 9, 22, 1, 31, 59, tzinfo=datetime.timezone(datetime.timedelta(seconds=10800)))

Or in a more readable form:

fulldate.astimezone(tz=timezone(timedelta(hours=3))).isoformat()
---------------------------
'2022-09-22T01:31:59 03:00'

This is 1AM in the next day but with a 3:00 offset. This is still the same time as 22PM at UTC.

It's also possible to just replace the UTC offset with another one, without changing the time values, using replace:

fulldate.replace(tzinfo=timezone(timedelta(hours=3))).isoformat()
----------------------------
'2022-09-21T22:31:59 03:00'

That's the original time with a different offset. That's no longer the same time as 2022-09-21T22:31:59Z

  • Related