from datetime import datetime
def parse_date_safely(date_string, format='%Y-%m-%d'):
"""
Parses a date string with error handling.
Args:
date_string (str): The date string to parse.
format (str): The expected date format.
Returns:
datetime: A datetime object if parsing is successful,
or None if parsing fails.
"""
try:
# Attempt to parse the date string
date_object = datetime.strptime(date_string, format)
return date_object
except ValueError:
# Handle cases where the date string doesn't match the format
print(f"Error: Invalid date format. Expected {format}, got {date_string}")
return None
except TypeError:
# Handle cases where the input is not a string
print(f"Error: Input must be a string. Got {type(date_string)}")
return None
def process_dates(date_strings):
"""
Processes a list of date strings, handling potential failures.
Args:
date_strings (list): A list of date strings to process.
Returns:
list: A list of datetime objects (or None for failed parses).
"""
results = []
for date_string in date_strings:
date_object = parse_date_safely(date_string)
results.append(date_object)
return results
if __name__ == '__main__':
# Example usage with test cases
date_list = [
"2023-10-26", # Valid date
"2023/10/27", # Invalid format
123, # Invalid type
"2023-12-31", # Valid date
"invalid-date" # Invalid date format
]
processed_dates = process_dates(date_list)
for i, date in enumerate(processed_dates):
print(f"Date {date_list[i]}: {date}")
Add your comment