Date String 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.


Technology Stack : datetime

Code Type : Date formatting function

Code Difficulty : Intermediate


                
                    
def format_date(date_str, format_str='%Y-%m-%d'):
    from datetime import datetime
    try:
        formatted_date = datetime.strptime(date_str, format_str).strftime(format_str)
        return formatted_date
    except ValueError:
        return "Invalid date format"                
              
Tags: