Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to reformat date in YYYY-MM-DD format using Python
Converting date strings from human-readable format like "23rd Jan 2021" to standardized "YYYY-MM-DD" format is a common task in data processing. Python provides several approaches to handle this conversion efficiently.
Understanding the Problem
We need to parse a date string where:
Day includes ordinal suffix (1st, 2nd, 3rd, 4th, etc.)
Month is abbreviated (Jan, Feb, Mar, etc.)
Year is a four-digit number (1900-2100)
The target format is ISO 8601 standard: "YYYY-MM-DD".
Method 1: Using String Manipulation
This approach splits the date string and manually converts each component ?
def solve(date):
months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
parts = date.split()
year = parts[2]
day = parts[0][:-2] # Remove ordinal suffix (st, nd, rd, th)
# Add leading zero if single digit
if len(day) < 2:
day = "0" + day
# Find month number and add leading zero if needed
month = str(months.index(parts[1]) + 1)
if len(month) < 2:
month = "0" + month
return f"{year}-{month}-{day}"
date = "23rd Jan 2021"
print(solve(date))
2021-01-23
Method 2: Using datetime Module
Python's datetime module provides more robust date parsing ?
import re
from datetime import datetime
def reformat_date(date_str):
# Remove ordinal suffixes (st, nd, rd, th)
clean_date = re.sub(r'(\d+)(st|nd|rd|th)', r'\1', date_str)
# Parse the cleaned date
parsed_date = datetime.strptime(clean_date, "%d %b %Y")
# Format to YYYY-MM-DD
return parsed_date.strftime("%Y-%m-%d")
date = "23rd Jan 2021"
print(reformat_date(date))
2021-01-23
Method 3: Using Dictionary Mapping
A cleaner approach using dictionary for month conversion ?
def format_date(date_str):
month_map = {
"Jan": "01", "Feb": "02", "Mar": "03", "Apr": "04",
"May": "05", "Jun": "06", "Jul": "07", "Aug": "08",
"Sep": "09", "Oct": "10", "Nov": "11", "Dec": "12"
}
parts = date_str.split()
day = parts[0][:-2].zfill(2) # Remove suffix and pad with zero
month = month_map[parts[1]]
year = parts[2]
return f"{year}-{month}-{day}"
# Test with multiple dates
test_dates = ["1st Jan 2020", "15th Mar 2021", "3rd Dec 2022"]
for date in test_dates:
print(f"{date} ? {format_date(date)}")
1st Jan 2020 ? 2020-01-01 15th Mar 2021 ? 2021-03-15 3rd Dec 2022 ? 2022-12-03
Comparison
| Method | Pros | Cons | Best For |
|---|---|---|---|
| String Manipulation | Simple, no imports | Manual validation | Basic conversion |
| datetime Module | Built-in validation | Requires regex for cleanup | Production code |
| Dictionary Mapping | Clean, readable | No date validation | Simple, fast conversion |
Conclusion
Use the datetime module for robust date parsing with validation. For simple conversions without validation, dictionary mapping provides clean and readable code. String manipulation works for basic cases but lacks error handling.
