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.
Introductory ⭐
- Harvard University Data Science: Learn R Basics for Data Science
- Standford University Data Science: Introduction to Machine Learning
- UC Davis Data Science: Learn SQL Basics for Data Science
- IBM Data Science: Professional Certificate in Data Science
- IBM Data Analysis: Professional Certificate in Data Analytics
- Google Data Analysis: Professional Certificate in Data Analytics
- IBM Data Science: Professional Certificate in Python Data Science
- IBM Data Engineering Fundamentals: Python Basics for Data Science
Intermediate ⭐⭐⭐
- Harvard University Learning Python for Data Science: Introduction to Data Science with Python
- Harvard University Computer Science Courses: Using Python for Research
- IBM Python Data Science: Visualizing Data with Python
- DeepLearning.AI Data Science and Machine Learning: Deep Learning Specialization
Advanced ⭐⭐⭐⭐⭐
- UC San Diego Data Science: Python for Data Science
- UC San Diego Data Science: Probability and Statistics in Data Science using Python
- Google Data Analysis: Professional Certificate in Advanced Data Analytics
- MIT Statistics and Data Science: Machine Learning with Python - from Linear Models to Deep Learning
- MIT Statistics and Data Science: MicroMasters® Program in Statistics and Data Science
🔎 Find Data Science Programs 👨💻 111,889 already enrolled
Disclaimer: Data Science Parichay is reader supported. When you purchase a course through a link on this site, we may earn a small commission at no additional cost to you. Earned commissions help support this website and its team of writers.
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.