In this article, we gonna show how to convert different input Date formats to a single output date format.
Given Date Formats :
Case 1 : “2019-3-6”
Case 2: “Wed, 6, March, 19”
Case 3: “Wednesday, 6, March, 9”
Case 4: “6-3-2019”
Output date format should be: 3/6/2019
// Importing datetime
import datetime
// First type of Date and it's format
inputDate0 = "2019-3-6"
DateFormat0 = "%Y-%m-%d"
// Second type of Date and it's format
inputDate1 = "Wed, 6, March, 19"
DateFormat1 = "%a, %d, %B, %y"
// Third type of Date and it's format
inputDate2 = "Wednesday, 6, March, 19"
DateFormat2 = "%A, %d, %B, %y"
// Fourth type of Date and it's format
inputDate3 = ""6-3-2019""
DateFormat3 = "%d-%m-%Y"
// Out date format
outPutDateFormat = "%m/%d/%y"
// Converting input date to Date type object
date0 = datetime.datetime.strptime(inputDate0 , DateFormat0 )
date1 = datetime.datetime.strptime(inputDate1 , DateFormat1 )
date2 = datetime.datetime.strptime(inputDate2 , DateFormat2 )
date3 = datetime.datetime.strptime(inputDate3 , DateFormat3 )
// Print different combination of dates as per output format
print datetime.date.strftime(date0, outPutDateFormat )
print datetime.date.strftime(date1, outPutDateFormat )
print datetime.date.strftime(date2, outPutDateFormat )
print datetime.date.strftime(date3, outPutDateFormat )
Output will be like this
6/3/2019
6/3/2019
6/3/2019
6/3/2019
Please check this official Python’s documentation for more info:
https://docs.python.org/2/library/datetime.html
How to Convert Different Date Formats to a Single Date format – Python