Home > Blockchain >  How to convert timezone to datetime and ISO 8601 format in python?
How to convert timezone to datetime and ISO 8601 format in python?

Time:06-23

How to convert a timezone string like 2022-06-23T05:00:00.006417 00:00Z to datetime and ISO 8601 format?

CodePudding user response:

Isn't that already the ISO format?

To parse it

Anyway as it is in ISO you can use datetime.fromisoformat(docs) to parse it, as it looks to be an iso format.

Following examples from the docs:

>>> from datetime import datetime
>>> datetime.fromisoformat('2011-11-04')
datetime.datetime(2011, 11, 4, 0, 0)
>>> datetime.fromisoformat('2011-11-04T00:05:23')
datetime.datetime(2011, 11, 4, 0, 5, 23)
>>> datetime.fromisoformat('2011-11-04 00:05:23.283')
datetime.datetime(2011, 11, 4, 0, 5, 23, 283000)
>>> datetime.fromisoformat('2011-11-04 00:05:23.283 00:00')
datetime.datetime(2011, 11, 4, 0, 5, 23, 283000, tzinfo=datetime.timezone.utc)
>>> datetime.fromisoformat('2011-11-04T00:05:23 04:00')   
datetime.datetime(2011, 11, 4, 0, 5, 23,
    tzinfo=datetime.timezone(datetime.timedelta(seconds=14400)))

Alternatively, if it's another format you can use datetime.strptime (docs) given some format

To format it

To iso-format it, you can use datetime.isoformat (docs).

Following examples from the docs:

>>> from datetime import datetime, timezone
>>> datetime(2019, 5, 18, 15, 17, 8, 132263).isoformat()
'2019-05-18T15:17:08.132263'
>>> datetime(2019, 5, 18, 15, 17, tzinfo=timezone.utc).isoformat()
'2019-05-18T15:17:00 00:00'

CodePudding user response:

Here is a function that converts strings like 2022-06-23T05:00:00.006417 00:00 to datetime objects.

import datetime
def str_to_datetime(str_time):
    return datetime.datetime.strptime(str_time, '%Y-%m-%dT%H:%M:%S.%f%z')

I think you have an extra Z in your string.

  • Related