Date-Time String Formatting Function

  • Share this:

Code introduction


This function converts a given date-time string to a specified format. If no format is specified, it defaults to 'YYYY-MM-DD HH:MM:SS'.


Technology Stack : datetime

Code Type : Date time processing

Code Difficulty : Intermediate


                
                    
import datetime

def time_formatter(date_string, format_string="%Y-%m-%d %H:%M:%S"):
    try:
        date_obj = datetime.datetime.strptime(date_string, "%Y-%m-%d %H:%M:%S")
        return date_obj.strftime(format_string)
    except ValueError:
        return "Invalid date format. Please use YYYY-MM-DD HH:MM:SS."                
              
Tags: