Open In App

Convert string to DateTime and vice-versa in Python

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

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

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'>

Read More: Create Python Datetime from string

How to Convert Datetime to String?

You can also convert a DateTime to a string for various purposes like reporting, custom formatting, or formatting for display. Let’s see various methods to convert datetime to string.

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

1. Convert Datetime to String using Time.strftime()

Python strftime() function is present in datetime module to create a string representation based on the specified format string. We are using this method to convert datetime to string in Python. 

Another similar function is available in the Python time module which converts a tuple or struct_time object to a string as specified by the format argument. 

Example: The program converts Datetime to String and imports the Python time module, which offers functions for handling time-related activities. The convert() function takes a tuple datetime_str as input, transforms it to a timestamp using time.mktime(), and then formats the timestamp into a string representation using the format “%b%d%Y%r” that was supplied.

Python3




import time
  
# Function to convert string to datetime
def convert(datetime_str):
    datetime_str = time.mktime(datetime_str)
    format = "%b %d %Y %r"  
    dateTime = time.strftime(format, time.gmtime(datetime_str))
    return dateTime
  
date_time = (2018, 12, 4, 10, 7, 00, 1, 48, 0)
print(convert(date_time))
print(type(convert(date_time)))


Output:

Dec 04 2018 04:37:00 AM
<class 'str'>

Time Complexity: O(1)
Auxiliary Space: O(1)

Learn More: How to Format date using strftime() in Python

2. Convert Datetime to String using Datetime

Bring the datetime module to convert datetime to String using the specified date and time, and create a datetime object. Create a format string that outlines the formatting requirements for the datetime object. 

To create a string in the desired format, use the DateTime object’s strftime() method. The format string is the argument for the strftime() function.

Example: The program imports the datetime module, which gives Python programmers access to classes for working with dates and times. The provided date and time values, March 14, 2022, at 15:30:00, are used to generate a datetime object. The datetime object is transformed into a string representation based on the format string using the strftime() method.

Python3




import datetime
  
datetime_object = datetime.datetime(2022, 3, 14, 15, 30, 0)
  
format_string = '%Y-%m-%d %H:%M:%S'
  
# Convert the datetime object to a string in the specified format
date_string = datetime_object.strftime(format_string)
  
print(date_string)
print(type(date_string))


Output:

2022-03-14 15:30:00
<class 'str'>

Time Complexity: O(1)
Auxiliary Space: O(1)

In this article, we have covered the methods to convert string to datetime and vice-versa. Converting datetime to strings or vice-versa can be very useful and convenient in Programming. You can use these methods to convert datetime to strings or vice-versa.

Also Read:



Last Updated : 18 Mar, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads