How to Convert String to DateTime?

In Python, users can sometimes enter a date as a string due to which we can not perform date-time operations on it. Operations like time difference, date comparison, working with time zones, etc. can not be done on string dates.

Let’s see the process of converting strings to dates with two methods.

Input: Dec 4 2018 10:07 AM 
Output: 2018-12-04 10:07:00
Explanation: In this, we are converting the string to Date Time.

1. Convert String to Datetime using Datetime.Strptime()

The Strptime() is available in the datetime module and is used for Date-Time conversion. This function changes the given string of Datetime into the desired format. 

Example: The program defines a function that converts the date and time represented as a string to a datetime object using the desired format. The conversion is performed using the datetime.strptime() method.

Python3




import datetime
  
# Function to convert string to datetime
def convert(date_time):
    format = '%b %d %Y %I:%M%p'
    datetime_str = datetime.datetime.strptime(date_time, format)
  
    return datetime_str
    
date_time = 'Dec 4 2018 10:07AM'
print(convert(date_time))
print(type(convert(date_time)))


Output:

2018-12-04 10:07:00
<class 'datetime.datetime'>)

2. Convert String to Datetime Using Dateutil Module

The Dateutil is a third-party module. The Dateutil module supports the parsing of dates in any string format. Internal facts about current world time zones are provided by this module. Parse() can convert a Python string to date-time format. The only parameter used is the string.

Example: The program imports the dateutil library’s parser module for converting string to datetime which has a function for parsing date and time strings. The Parser.parse() function recognizes the format automatically, which transforms the string “Jun 23 2022 07:31 PM” into a DateTime object.

Python3




from dateutil import parser
  
DT = parser.parse("Jun 23 2022 07:31PM")
  
print(DT)
print(type(DT))


Output:

2022-06-23 19:31:00
<class 'datetime.datetime'>

Convert string to DateTime and vice-versa in Python

A common necessity in many programming applications is dealing with dates and times. Python has strong tools and packages that simplify handling date and time conversions. This article will examine how to effectively manipulate and format date and time values in Python by converting Strings to Datetime objects and back. We will cover the article into two parts:

  • Python Convert String to DateTime
  • Python Convert Datetime to String

Similar Reads

How to Convert String to DateTime?

In Python, users can sometimes enter a date as a string due to which we can not perform date-time operations on it. Operations like time difference, date comparison, working with time zones, etc. can not be done on string dates....

How to Convert Datetime to String?

...

Contact Us