1. from datetime import datetime
  2. def parse_date_safely(date_string, format='%Y-%m-%d'):
  3. """
  4. Parses a date string with error handling.
  5. Args:
  6. date_string (str): The date string to parse.
  7. format (str): The expected date format.
  8. Returns:
  9. datetime: A datetime object if parsing is successful,
  10. or None if parsing fails.
  11. """
  12. try:
  13. # Attempt to parse the date string
  14. date_object = datetime.strptime(date_string, format)
  15. return date_object
  16. except ValueError:
  17. # Handle cases where the date string doesn't match the format
  18. print(f"Error: Invalid date format. Expected {format}, got {date_string}")
  19. return None
  20. except TypeError:
  21. # Handle cases where the input is not a string
  22. print(f"Error: Input must be a string. Got {type(date_string)}")
  23. return None
  24. def process_dates(date_strings):
  25. """
  26. Processes a list of date strings, handling potential failures.
  27. Args:
  28. date_strings (list): A list of date strings to process.
  29. Returns:
  30. list: A list of datetime objects (or None for failed parses).
  31. """
  32. results = []
  33. for date_string in date_strings:
  34. date_object = parse_date_safely(date_string)
  35. results.append(date_object)
  36. return results
  37. if __name__ == '__main__':
  38. # Example usage with test cases
  39. date_list = [
  40. "2023-10-26", # Valid date
  41. "2023/10/27", # Invalid format
  42. 123, # Invalid type
  43. "2023-12-31", # Valid date
  44. "invalid-date" # Invalid date format
  45. ]
  46. processed_dates = process_dates(date_list)
  47. for i, date in enumerate(processed_dates):
  48. print(f"Date {date_list[i]}: {date}")

Add your comment