Menu Close

How to Convert String to DateTime in Python

convert string to DateTime in Python

Hi Python Developers, In this article, you will learn everything about how to convert string to DateTime in Python with the help of proper examples. This is one of the most common problems which occurs in the software development field. Here we will use strptime() function which is defined inside Python built-in modules that are called DateTime and time.

Introduction of strptime() method

The strptime() is a method that is defined inside DateTime and time module that made it easy to parse string DateTime to DateTime and time object.DateTime is a Python built-in module that means you don’t need to install it by using pip. This is one of the best functions to convert string to DateTime object. It takes two parameters, the first is string DateTime and the second is the format.

Note:- Both the arguments are mandatory and it should be a string type.

Syntax

This is the syntax of the strptime() method.

strptime(datetime_string, format)

Same function available inside Python time module which syntax is.

strptime(time_string[, format])

But here we will use strptime() method which is defined inside the Python DateTime module.

Python strptime() Method Examples

In this examples series, we will take multiple examples so that you don’t have any confusion regarding strptime() method and its usages.

Format Table

This format table will be very helpful when you are going to convert string to DateTime in Python.
You can pick any format directive as per your choice.

Format CodeMeaningExample
%aWeekday nameSun, Mon
%AFull weekday name.Sunday, Monday
%wWeekday as a decimal number.0,1,2,3,…6
%dDay of the month as a zero-padded decimal.01,02,03,….31
%-dDay of the month a decimal number.1,2,3,…31
%bMonth name.Jun, Feb
%BFull month name.January, February,…
%mMonth as a zero-padded decimal.01, 02, ….12
%-mMonth as a decimal.1,2,3,….12
%yA Year without century as a zero-padded decimal.00,01, 02, ..99
%-yA year without century decimal number.0,1,2,..,99
%YA full year without century as a decimal number.2020, 2021, 2022 etc.
%HHour ( 24-hour Clock ) as a zero-padded decimal number.00, 01, 02,…,23
%-HHour ( 24-hour Clock ) as a decimal number.0, 1, 2,…,23
%IHour ( 12-hour Clock ) as a zero-padded decimal number.01, 02,…,12
%-IHour ( 12-hour Clock ) as a decimal number.1, 2,…,12
%pLocal’s AM and PMAM, PM
%MMinute as a zero-padded decimal number.00, 01, 02,…,59
%-MMinute as a decimal number.0, 1, 2,…,59
%SSecond as a zero-padded decimal number.00, 01, 02,…,59
%-SSecond as a decimal number.0, 1, 2,…,59
%fMicrosecond as a zero-padded decimal number on the left.000000-999999
%cLocal appropriate date and time representation.Sun Jan 9 13:50:29 2022
%xLocal appropriate date representation.01/09/22
%XLocal appropriate time representation.13:50:29

Convert String to Datetime Object

The below code illustrates how to convert string to DateTime object in Python.

Example:- String to DateTime Conversion


from datetime import datetime

datetime_string = '2022-01-15 19:03:28'
format_string = '%Y-%m-%d %H:%M:%S'

#convert into datetime object
datetime_object = datetime.strptime(datetime_string, format_string)
print(datetime_object)

Output will be :- 2022-01-15 19:03:28

The type of datetime_object will be the DateTime object, you can check the type using the type() function.

#check the type
print(type(datetime_object))

The output will be:

<class 'datetime.datetime'>

Convert Sring to Date Object

This example illustrates a process to convert string to date objects using strptime() function. Here we will use the date() function to extract the only date part from the DateTime object after conversion.

Example:- String to Date Conversion


from datetime import datetime

datetime_string = '2022-01-15'
format_string = '%Y-%m-%d'

#convert into datetime object
date_object = datetime.strptime(datetime_string, format_string).date()
print(date_object)

The Output will be:- 2022-01-15

Again you can use the type() function to check the type of date_object. This time type will be the date object.


#check the type
print(type(date_object))

The output will be:-

<class 'datetime.date'>

Convert Sring to Time Object

This example illustrates a process to convert string to time object using strptime() function. Here we will use the time() function to extract the only time part from the DateTime object.

Example:- String to Time Conversion


from datetime import datetime

datetime_string = '2022-01-15 19:03:28'
format_string = '%Y-%m-%d %H:%M:%S'

#convert into datetime object
datetime_object = datetime.strptime(datetime_string, format_string)

time_object = datetime_object.time()
print(time_object)

The Output will be:- 19:03:28

Again you can use the type() function to check the type of time_object. This time type will be the time object.


#check the type
print(type(time_object))

Output

<class 'datetime.time'>

The strptime() function will not work properly if the string argument does not match with the format argument.


from datetime import datetime

datetime_string = '2022-01-15 19:03:28'
format_string = '%Y-%m-%d %H::%M::%S'

#convert into datetime object
datetime_object = datetime.strptime(datetime_string, format_string)

print(datetime_object)

Output

Traceback (most recent call last):
  File "C:\Users\Vishvajit\Desktop\PF Article\Python Basic part1\test.py", line 8, in <module>
    datetime_object = datetime.strptime(datetime_string, format_string)
  File "C:\Users\Vishvajit\AppData\Local\Programs\Python\Python38\lib\_strptime.py", line 568, in _strptime_datetime
    tt, fraction, gmtoff_fraction = _strptime(data_string, format)
  File "C:\Users\Vishvajit\AppData\Local\Programs\Python\Python38\lib\_strptime.py", line 349, in _strptime
    raise ValueError("time data %r does not match format %r" %
ValueError: time data '2022-01-15 19:03:28' does not match format '%Y-%m-%d %H::%M::%S'

Handling ValueError

To handle value error you have to use try-except block to catch the proper exception message.
Let’s see how can you do that.

Example: Handling Exception


from datetime import datetime
try:
    datetime_string = '2022-01-15 19:03:28'
    format_string = '%Y-%m-%d %H::%M::%S'

    #convert into datetime object
    datetime_object = datetime.strptime(datetime_string, format_string)

    print(datetime_object)
except Exception as e:
    print("Exception is:- ", e)

Output

Exception is:- time data ‘2022-01-15 19:03:28’ does not match format ‘%Y-%m-%d %H::%M::%S’

Now, you can easily understand what exception is occurring and you can solve it easily.

Concusion

So in this article, you have seen how to convert string to DateTime in Python with the help of multiple examples so that you don’t have any confusion regarding DateTime conversion.
The strptime() is a very helpful method defined inside the Python DateTime module to convert string to DateTime.

The strptime() accepts two parameters that are DateTime string and format. The format string parameters should be matched with DateTime string.

I hope this article is going to be very helpful for you. If you like this article, please share and keep visiting for this type of interesting article.

Thanks for your valuable time 👏👏👏

Previous Article
Next Article

Related Posts