from dateutil import parser
def reformat_date(date_string, desired_format="%Y-%m-%d"):
"""
Detects the format of a date string, parses it, and reformats it to the desired format.
Args:
date_string: The date string to be parsed and reformatted.
desired_format: The desired output format for the date (default: YYYY-MM-DD).
Returns:
A string representing the date in the desired format, or None if the date string could not be parsed.
"""
try:
parsed_date = parser.parse(date_string)
reformatted_date = parsed_date.strftime(desired_format)
return reformatted_date
except ValueError:
return None
# Example usage:
date_str1 = "2023/10/26"
date_str2 = "October 26, 2023"
date_str3 = "26-Oct-23"
date_str4 = "Invalid Date"
reformatted_date1 = reformat_date(date_str1)
reformatted_date2 = reformat_date(date_str2)
reformatted_date3 = reformat_date(date_str3, "%d/%m/%Y") # Custom desired format
reformatted_date4 = reformat_date(date_str4)
print(f"Original: {date_str1}, Reformatted: {reformatted_date1}")
print(f"Original: {date_str2}, Reformatted: {reformatted_date2}")
print(f"Original: {date_str3}, Reformatted: {reformatted_date3}")
print(f"Original: {date_str4}, Reformatted: {reformatted_date4}")
ZnJvbSBkYXRldXRpbCBpbXBvcnQgcGFyc2VyCgpkZWYgcmVmb3JtYXRfZGF0ZShkYXRlX3N0cmluZywgZGVzaXJlZF9mb3JtYXQ9IiVZLSVtLSVkIik6CiAgIiIiCiAgRGV0ZWN0cyB0aGUgZm9ybWF0IG9mIGEgZGF0ZSBzdHJpbmcsIHBhcnNlcyBpdCwgYW5kIHJlZm9ybWF0cyBpdCB0byB0aGUgZGVzaXJlZCBmb3JtYXQuCgogIEFyZ3M6CiAgICBkYXRlX3N0cmluZzogVGhlIGRhdGUgc3RyaW5nIHRvIGJlIHBhcnNlZCBhbmQgcmVmb3JtYXR0ZWQuCiAgICBkZXNpcmVkX2Zvcm1hdDogVGhlIGRlc2lyZWQgb3V0cHV0IGZvcm1hdCBmb3IgdGhlIGRhdGUgKGRlZmF1bHQ6IFlZWVktTU0tREQpLgoKICBSZXR1cm5zOgogICAgQSBzdHJpbmcgcmVwcmVzZW50aW5nIHRoZSBkYXRlIGluIHRoZSBkZXN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