Converting string ‘yyyy-mm-dd’ into DateTime in Python
In this article, we are going to convert DateTime string of the format ‘yyyy-mm-dd’ into DateTime using Python.
yyyy-mm-dd stands for year-month-day .
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course
We can convert string format to datetime by using the strptime() function. We will use the ‘%Y/%m/%d’ format to get the string to datetime.
Syntax:
datetime.datetime.strptime(input,format)
Parameter:
- input is the string datetime
- format is the format – ‘yyyy-mm-dd’
- datetime is the module
Example: Python program to convert string datetime format to datetime
Python3
# import the datetime moduleimport datetime # datetime in string format for may 25 1999input = '2021/05/25' # formatformat = '%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()) |
2021-05-25
Example 2: Convert a list of string DateTime to DateTime
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()) |
2021-05-25 2020-05-25 2019-02-15 1999-02-04


