Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

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

  • Difficulty Level : Basic
  • Last Updated : 23 Aug, 2021

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 .

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 module
import datetime
  
# datetime in string format for may 25 1999
input = '2021/05/25'
  
# format
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

Example 2: Convert a list of string DateTime to DateTime

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

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!