Skip to Content

Convert String to Datetime in Python

In this tutorial, we will look at how to convert a date in string form to a datetime object in Python with the help of some examples.

How to convert string to datetime in Python?

You can use the strptime() function defined in the datetime class to convert a string to a datetime object in Python. The following is the syntax.

from datetime import datetime
datetime.strptime(date_string, format)

Pass the string and the desired format for the date as arguments to the function. It returns a datetime object. Note that the string must be consistent with the format parameter for the function to correctly parse the string.

Examples

Let’s look at some examples of using the strptime() function to convert a string to a date.

Let’s say we have a string containing the date "2021-12-04" and we want to convert it to a datetime object in the same format, that is, YYYY-MM-DD.

from datetime import datetime

# date string
date_str = "2021-12-04"
# date string to datetime
date = datetime.strptime(date_str, "%Y-%m-%d")
# display date and its type
print(date)
print(type(date))

Output:

2021-12-04 00:00:00
<class 'datetime.datetime'>

Here we pass the string and the format string "%Y-%m-%d" to the strptime() function. The returned object is a datetime object. You can see that the time component in our date object is 00:00:00 because our date string didn’t have any time part.

You can find the complete list of format codes that can be used in the strptime() function here.

Let’s now look at an example with a date string having a time component.

from datetime import datetime

# date string
date_str = "2021-12-04 18:30:00"
# date string to datetime
date = datetime.strptime(date_str, "%Y-%m-%d %H:%M:%S")
# display date and its type
print(date)
print(type(date))

Output:

2021-12-04 18:30:00
<class 'datetime.datetime'>

Here we get the date with the time component. Note that we had to modify our format string to accommodate the time component in the date string.

What if the date string is not consistent with the format string? Let’s find out. In the above example, the date string is in the form YYYY-MM-DD, what if we use the format string for the format YYYY/MM/DD?

from datetime import datetime

# date string
date_str = "2021-12-04"
# date string to datetime
date = datetime.strptime(date_str, "%Y/%m/%d")
# display date and its type
print(date)
print(type(date))

Output:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Input In [10], in <module>
      4 date_str = "2021-12-04"
      5 # date string to datetime
----> 6 date = datetime.strptime(date_str, "%Y/%m/%d")
      7 # display date and its type
      8 print(date)

File ~/miniforge3/envs/dsp/lib/python3.8/_strptime.py:568, in _strptime_datetime(cls, data_string, format)
    565 def _strptime_datetime(cls, data_string, format="%a %b %d %H:%M:%S %Y"):
    566     """Return a class cls instance based on the input string and the
    567     format string."""
--> 568     tt, fraction, gmtoff_fraction = _strptime(data_string, format)
    569     tzname, gmtoff = tt[-2:]
    570     args = tt[:6] + (fraction,)

File ~/miniforge3/envs/dsp/lib/python3.8/_strptime.py:349, in _strptime(data_string, format)
    347 found = format_regex.match(data_string)
    348 if not found:
--> 349     raise ValueError("time data %r does not match format %r" %
    350                      (data_string, format))
    351 if len(data_string) != found.end():
    352     raise ValueError("unconverted data remains: %s" %
    353                       data_string[found.end():])

ValueError: time data '2021-12-04' does not match format '%Y/%m/%d'

We get an error. This is because the format string didn’t match the format of the date string.

In this tutorial, we looked at how to convert a date string in Python to a datetime object using the strptime() function. You can similarly use the strftime() function to do the reverse operation, that is, convert datetime object to a date string.

You might also be interested in –


Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.


Author

  • Piyush is a data scientist passionate about using data to understand things better and make informed decisions. In the past, he's worked as a Data Scientist for ZS and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects.