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