fork download
  1. from dateutil import parser
  2. from datetime import datetime
  3.  
  4. def reformat_date(date_string, desired_format="%Y-%m-%d"):
  5. """
  6. Detects the format of the date string, parses it, and reformats it into the desired format.
  7.  
  8. :param date_string: The date string to be reformatted.
  9. :param desired_format: The desired format for the output date string (default is "%Y-%m-%d").
  10. :return: The reformatted date string.
  11. """
  12. try:
  13. # Parse the date string using dateutil's parser
  14. parsed_date = parser.parse(date_string)
  15.  
  16. # Reformat the parsed date into the desired format
  17. reformatted_date = parsed_date.strftime(desired_format)
  18.  
  19. return reformatted_date
  20. except ValueError as e:
  21. return f"Error parsing date: {e}"
  22.  
  23. # Example usage:
  24. date_input = "March 5, 2023"
  25. desired_format = "%d-%m-%Y"
  26. reformatted_date = reformat_date(date_input, desired_format)
  27. print(reformatted_date) # Output: "05-03-2023"
Success #stdin #stdout 0.04s 11808KB
stdin
Standard input is empty
stdout
05-03-2023