fork download
  1. from dateutil import parser
  2.  
  3. def reformat_date(date_string, desired_format="%Y-%m-%d"):
  4. """
  5. Detects the format of a date string, parses it, and reformats it to the desired format.
  6.  
  7. Args:
  8. date_string: The date string to be parsed and reformatted.
  9. desired_format: The desired output format for the date (default: YYYY-MM-DD).
  10.  
  11. Returns:
  12. A string representing the date in the desired format, or None if the date string could not be parsed.
  13. """
  14. try:
  15. parsed_date = parser.parse(date_string)
  16. reformatted_date = parsed_date.strftime(desired_format)
  17. return reformatted_date
  18. except ValueError:
  19. return None
  20.  
  21. # Example usage:
  22. date_str1 = "2023/10/26"
  23. date_str2 = "October 26, 2023"
  24. date_str3 = "26-Oct-23"
  25. date_str4 = "Invalid Date"
  26.  
  27. reformatted_date1 = reformat_date(date_str1)
  28. reformatted_date2 = reformat_date(date_str2)
  29. reformatted_date3 = reformat_date(date_str3, "%d/%m/%Y") # Custom desired format
  30. reformatted_date4 = reformat_date(date_str4)
  31.  
  32. print(f"Original: {date_str1}, Reformatted: {reformatted_date1}")
  33. print(f"Original: {date_str2}, Reformatted: {reformatted_date2}")
  34. print(f"Original: {date_str3}, Reformatted: {reformatted_date3}")
  35. print(f"Original: {date_str4}, Reformatted: {reformatted_date4}")
Success #stdin #stdout 0.06s 11976KB
stdin
Standard input is empty
stdout
Original: 2023/10/26, Reformatted: 2023-10-26
Original: October 26, 2023, Reformatted: 2023-10-26
Original: 26-Oct-23, Reformatted: 26/10/2023
Original: Invalid Date, Reformatted: None