Date Formatting Function

  • Share this:

Code introduction


This function takes a date string and a format string as input, and formats the date string according to the specified format. If the date format is incorrect, it returns an error message.


Technology Stack : datetime, babel.dates

Code Type : Date formatting

Code Difficulty : Intermediate


                
                    
def format_date(date_str, format_str):
    from datetime import datetime
    from babel.dates import format_date

    try:
        datetime_obj = datetime.strptime(date_str, '%Y-%m-%d')
        return format_date(datetime_obj, format_str)
    except ValueError:
        return "Invalid date format"