Table of contents
1.
Introduction
2.
How to Convert String to DateTime?
2.1.
Using datetime.strptime()
3.
Using dateutil Module
3.1.
Installation
4.
How to Convert Datetime to String?
4.1.
Using time.strftime()
4.2.
Using datetime Module Directly
5.
Frequently Asked Questions 
5.1.
What is the purpose of converting strings to datetime in Python?
5.2.
What happens if the format does not match in strptime()?
5.3.
When should I use dateutil instead of strptime()?
6.
Conclusion
Last Updated: Dec 20, 2024
Easy

Convert String to DateTime in Python

Author Sinki Kumari
0 upvote

Introduction

Converting strings to DateTime in Python is a common task for handling date and time data in programming. Python's datetime module offers efficient methods to parse strings into DateTime objects. This process is essential for tasks like scheduling, logging, or data analysis where date-time manipulation is required.

Convert String to DateTime in Python

In this article, you will learn how to convert a string to a datetime object in Python and vice versa. We’ll discuss some common methods and provide examples to help you understand the concepts better.

How to Convert String to DateTime?

Converting strings to datetime objects allows you to manipulate and format dates efficiently. Python provides built-in modules and functions to make this process easier.

Using datetime.strptime()

The strptime() method from Python’s datetime module is the most commonly used way to convert strings to datetime objects.

Syntax

from datetime import datetime

#syntax
datetime.strptime(date_string, format)

 

  • date_string: The string representing the date and time.
     
  • format: The format string defining the expected structure of the input.
     

Example

from datetime import datetime

# Convert string to datetime
date_string = "2023-12-12 14:30:00"
format = "%Y-%m-%d %H:%M:%S"
date_time_obj = datetime.strptime(date_string, format)

print("Datetime Object:", date_time_obj)
You can also try this code with Online Python Compiler
Run Code


Output

Datetime Object: 2023-12-12 14:30:00


Explanation

  • %Y: Represents the year (e.g., 2023).
     
  • %m: Represents the month (01-12).
     
  • %d: Represents the day of the month (01-31).
     
  • %H: Represents the hour (00-23).
     
  • %M: Represents the minute (00-59).
     
  • %S: Represents the second (00-59).
     

This method is efficient with a time complexity of O(n), where n is the length of the string being parsed.

Using dateutil Module

The dateutil module is another powerful tool for working with dates and times. It simplifies the conversion process and can handle various date formats without explicitly specifying the format.

Installation

To use the dateutil module, install it first:

pip install python-dateutil


Example

from dateutil import parser
# Convert string to datetime
date_string = "12th December 2023, 2:30 PM"
date_time_obj = parser.parse(date_string)
print("Datetime Object:", date_time_obj)
You can also try this code with Online Python Compiler
Run Code


Output

Datetime Object: 2023-12-12 14:30:00


Explanation

The parser.parse() method automatically detects and interprets various date formats. It’s convenient for parsing human-readable dates.

How to Convert Datetime to String?

Sometimes, you may need to convert a datetime object back to a string. Python provides several methods to achieve this.

Using time.strftime()

The strftime() method formats a datetime object as a string according to the specified format.

Syntax

from time import strftime

# Syntax of strftime()
datetime_obj.strftime(format)

 

  • datetime_obj: The datetime object to be formatted.
     
  • format: The format string defining the output structure.
     

Example

from datetime import datetime

# Create a datetime object
date_time_obj = datetime(2023, 12, 12, 14, 30, 0)

# Convert datetime to string
format = "%Y-%m-%d %H:%M:%S"
date_string = date_time_obj.strftime(format)

print("String Representation:", date_string)
You can also try this code with Online Python Compiler
Run Code


Output

String Representation: 2023-12-12 14:30:00
You can also try this code with Online Python Compiler
Run Code


Explanation

The strftime() method uses the same format specifiers as strptime(), allowing you to define the desired string format.

Using datetime Module Directly

The isoformat() method of the datetime module can also convert a datetime object to a string in ISO 8601 format.

Example

from datetime import datetime

# Create a datetime object
date_time_obj = datetime(2023, 12, 12, 14, 30, 0)

# Convert datetime to ISO 8601 string
date_string = date_time_obj.isoformat()

print("ISO 8601 String Representation:", date_string)
You can also try this code with Online Python Compiler
Run Code


Output

ISO 8601 String Representation: 2023-12-12T14:30:00


Explanation

This method is useful when working with systems or APIs that use ISO 8601 formats.

Frequently Asked Questions 

What is the purpose of converting strings to datetime in Python?

Converting strings to datetime allows developers to perform various operations like date arithmetic, formatting, or extracting specific date components.

What happens if the format does not match in strptime()?

If the format does not match, Python raises a ValueError. Ensure the format string accurately represents the structure of the input string.

When should I use dateutil instead of strptime()?

Use dateutil when the input date format is ambiguous or varies, as it can parse multiple formats without explicitly specifying one.

Conclusion

In this article, we discussed how to convert strings to datetime objects and vice versa in Python using methods like datetime.strptime(), dateutil.parser.parse(), time.strftime(), and datetime.isoformat(). With these methods, you can handle various date and time conversions easily. By understanding and implementing these techniques, you’ll be better equipped to manage date and time data in your projects effectively.

You can also check out our other blogs on Code360.

Live masterclass