Program to reformat date in YYYY-MM-DD format using Python

PythonServer Side ProgrammingProgramming

Suppose we have a date string in the format "Day Month Year" format where day's are like [1st, 2nd, ..., 30th, 31st], months are in [Jan, Feb, ... Nov, Dec] format and year is a four-digit numeric value in range 1900 to 2100, we have to convert this date into "YYYY-MM-DD" format.

So, if the input is like date = "23rd Jan 2021", then the output will be 2021-01-23

To solve this, we will follow these steps −

  • Months:= ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]

  • string:= split the date and form a list like [day, month, year] format

  • year := string[2]

  • day := string[0] by removing last two characters

  • if day is single digit number, then

    • concatenate "0" with day

  • month := convert string[1] to month using Month list

  • if month is single digit number, then

    • concatenate "0" with month

  • return (year, month, day) in "YYYY-MM-DD" format

Example (Python)

Let us see the following implementation to get better understanding −

 Live Demo

def solve(date):
   Months=["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]

   year = string[2]
   day = string[0][:-2]

   if len(day)<2:

   month = str(Months.index(string[1])+1)

   if len(month)<2:

   return "{0}-{1}-{2}".format(year, month, day)

date = "23rd Jan 2021"


"23rd Jan 2021"


Published on 17-May-2021 12:17:10