close

How to convert Python’s .isoformat() string back into datetime object

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to convert Python’s .isoformat() string back into datetime object in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

How to convert Python’s .isoformat() string back into datetime object?

  1. How to convert Python's .isoformat() string back into datetime object?

    As of Python 3.7 there is a method datetime.fromisoformat() which is exactly the reverse for isoformat().

  2. convert Python's .isoformat() string back into datetime object

    As of Python 3.7 there is a method datetime.fromisoformat() which is exactly the reverse for isoformat().

Method 1

Python 3.7+

As of Python 3.7 there is a method datetime.fromisoformat() which is exactly the reverse for isoformat().

Older Python

If you have older Python, then this is the current best “solution” to this question:

pip install python-dateutil

Then…

import datetime
import dateutil

def getDateTimeFromISO8601String(s):
    d = dateutil.parser.parse(s)
    return d

Method 2

Try this:

>>> def gt(dt_str):
...     dt, _, us = dt_str.partition(".")
...     dt = datetime.datetime.strptime(dt, "%Y-%m-%dT%H:%M:%S")
...     us = int(us.rstrip("Z"), 10)
...     return dt + datetime.timedelta(microseconds=us)

Usage:

>>> gt("2008-08-12T12:20:30.656234Z")
datetime.datetime(2008, 8, 12, 12, 20, 30, 656234)

Conclusion

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read