How to convert a timezone string like 2022-06-23T05:00:00.006417+00:00Z
to datetime and ISO 8601 format?
Asked
Active
Viewed 1,422 times
-1

Talha Tayyab
- 8,111
- 25
- 27
- 44

fizzbuzzzzz
- 3
- 5
-
Be sure to actually search, the next time :) This question has been asked before. This answer is great, and shows a valid warning. https://stackoverflow.com/a/49784038/3806354 (that fromisoformat doesn't work with arbitrary iso strings) – Casper Bang Jun 23 '22 at 05:28
1 Answers
0
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'

Casper Bang
- 793
- 2
- 6
- 24
-
Instead of posting a whole bunch of examples, you could just provide an answer to the OP's question, or just flag the question as a duplicate? – AlexK Jun 23 '22 at 21:54
-
I was trying to, in an indirect way, say "you can easily google that or read the manual", but it's a valid criticism, AlexK :) Sorry about that. – Casper Bang Jun 24 '22 at 10:31