Converting string ‘yyyy-mm-dd’ into DateTime in Python

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 Datetime string of the format ‘yyyy-mm-dd'(yyyy-mm-dd stands for year-month-day) into Datetime using Python.
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.
Converting Strings to datetime in Python
We can convert string ‘yyyy-mm-dd’ 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.
Python Convert String Datetime Format to Datetime using Strptime()
We can convert Python date to a string using the strptime() function with Input(). We will use the ‘%Y/%m/%d’ format to get the string to datetime.
Python3
import datetime# datetime in string format for may 25 1999input = '2021/05/25'format = '%Y/%m/%d'# convert from string format to datetime formatdatetime = datetime.datetime.strptime(input, format)# get the date from the datetime using date()# functionprint(datetime.date()) |
Output
2021-05-25
Python DateUtil Converting string to a dateTime using dateutil.parser.parse()
We can convert Python data to string using dateutil.parser.parse() function from the dateutil library provides a more flexible approach to parsing and converting date strings.
Python3
from dateutil.parser import parsedef convert_to_datetime(input_str, parserinfo=None): return parse(input_str, parserinfo=parserinfo)# Example usagedate_string = '2023-07-25'result_datetime = convert_to_datetime(date_string)print(result_datetime) |
Output
2023-07-25 00:00:00
Python Convert String Datetime Format to Datetime using datetime.strptime()
We can convert Python date to a string using datetime.strptime(). Python’s datetime.strptime() method allows us to parse a date string with a specified format and convert it into an datetime object.
Python3
# import the datetime moduleimport datetime# datetime in string format for list of datesinput = ['2021/05/25', '2020/05/25', '2019/02/15', '1999/02/4']# formatformat = '%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



