Open In App

Converting string into DateTime in Python

Last Updated : 20 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Working with dates and times is a common task in programming, and Python offers a powerful datetime module to handle date and time-related operations.

In this article, we are going to convert the string of the format ‘yyyy-mm-dd’ (yyyy-mm-dd stands for year-month-day) into a DateTime object using Python.

Example:

Input: '2023-07-25'
Output: 2023-07-25  11:30:00
Explanation: In This, we are converting the string 'yyyy-mm-dd' to Datetime format in Python.

Note: There are multiple ways of writing dates in string format like yyyy-mm-dd, dd/mm/yyyy, etc. We can change any string date format to DateTime format using these methods.

How to Convert Strings to DateTime in Python?

We can convert the string into DateTime using different approaches and methods. Choose the appropriate method based on your requirements and handle invalid date strings gracefully to ensure the execution of your Python programs. Let’s look at each method below:

  1. Using strptime()
  2. Using dateutil.parser.parse()
  3. Using datetime.strptime()

Convert String Date to DateTime using strptime()

We can convert string date to a DataTime object using the strptime() function from datetime module with Input(). We will use the  ‘%Y/%m/%d’  format to get the string to DateTime.

Example:

Python3




import datetime
 
# datetime in string format for may 25 1999
input = '2021/05/25'
format = '%Y/%m/%d'
 
# convert from string format to datetime format
datetime = datetime.datetime.strptime(input, format)
 
# get the date from the datetime using date()
# function
print(datetime.date())


Output:

2021-05-25

Convert String to DateTime Objects in Python using dateutil.parser.parse()

We can convert string date to DateTime format using dateutil.parser.parse() function from the dateutil library. It provides a more flexible approach to parsing and converting date strings.

Python3




from dateutil.parser import parse
 
def convert_to_datetime(input_str, parserinfo=None):
    return parse(input_str, parserinfo=parserinfo)
 
# Example usage
date_string = '2023-07-25'
result_datetime = convert_to_datetime(date_string)
print(result_datetime)


Output:

2023-07-25  00:00:00

Read more: Using dateutil to parse dates.

Convert List of String Dates to DateTime using datetime.strptime()

We can convert a list of string dates to a DateTime object using datetime.strptime(). Python’s datetime.strptime() method allows us to parse a date string with a specified format and convert it into a datetime object.

Python3




# import the datetime module
import datetime
 
# datetime in string format for list of dates
input = ['2021/05/25', '2020/05/25', '2019/02/15', '1999/02/4']
 
# format
format = '%Y/%m/%d'
for i in input:
   
    # convert from string format to datetime format
    # and get the date
    print(datetime.datetime.strptime(i, format).date())


Output:

2021-05-25
2020-05-25
2019-02-15
1999-02-04

Troubleshooting strptime() Errors

strptime() will give you ValueError if the input string can’t be parsed in the given format.

You can try ‘try and except’ blocks to find the possible solution of the ValueError.

Example:

Python3




from datetime import datetime
# error as 2021 is not a leap year
date_string = "2021-02-29"
date_format = "%Y-%m-%d"
# Attempt to convert string to datetime
try:
    date_object = datetime.strptime(date_string, date_format)
    print(date_object)
except ValueError as e:
    print("Error:", e)


Output

Error: day is out of range for month

We have covered different methods to convert string the date string to DateTime format in Python. DateTime format in Python is very useful when operating on data as dates like finding the number of days between 2 dates.

It’s very important to keep dates in DateTime format if you have to perform operations on date. The interpreter will treat “yyyy-mm-dd” as a string if you don’t change it, making it impossible to perform the DateTime operation on it.

Similar Reads:



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads