
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Program to reformat date in YYYY-MM-DD format using Python
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 −
def solve(date): Months=["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] string=date.split() year = string[2] day = string[0][:-2] if len(day)<2: day="0"+day month = str(Months.index(string[1])+1) if len(month)<2: month="0"+month return "{0}-{1}-{2}".format(year, month, day) date = "23rd Jan 2021" print(solve(date))
Input
"23rd Jan 2021"
Output
2021-01-23
- Related Articles
- Java Program to format date in mm-dd-yyyy hh:mm:ss format
- MySQL query to convert YYYY-MM-DD to DD Month, YYYY date format
- Convert MySQL date format from yyyy-mm-ddThh:mm:ss.sssZ to yyyy-mm-dd hh:mm:ss ?
- How to format JavaScript date into yyyy-mm-dd format?
- How to parse Date from String in the format: dd/MM/yyyy to dd/MM/yyyy in java?
- Accepting date strings (MM-dd-yyyy format) using Java regex?
- MySQL date format DD/MM/YYYY select query?
- MySQL date format to convert dd.mm.yy to YYYY-MM-DD?
- How to format a string to date in as dd-MM-yyyy using java?
- Get date format DD/MM/YYYY with MySQL Select Query?
- Get today's date in (YYYY-MM-DD) format in MySQL?
- Change date format (in DB or output) to dd/mm/yyyy in PHP MySQL?
- How to convert Python date string mm/dd/yyyy to datetime?
- How to insert mm/dd/yyyy format dates in MySQL?
- How to Convert YYYY-MM-DD to Standard Date in Excel?
