Fix comparing two date strings when they may or may not have microseconds
Fix comparing two date strings when they may or may not have microseconds
I'm getting errors with this function:
python
def compare_dates(date1: str, date2: str) -> str: date1_obj = datetime.strptime(date1, "%Y-%m-%dT%H:%M:%S") date2_obj = datetime.strptime(date2, "%Y-%m-%dT%H:%M:%S") return date1 if date1_obj > date2_obj else date2
Because the input sometimes includes microseconds. Is there a clearer way of dealing with this than what I've done?
python
def compare_dates(date1: str, date2: str) -> str: date_format = "%Y-%m-%dT%H:%M:%S" date1_obj = datetime.strptime(date1.split(".")[0], date_format) date2_obj = datetime.strptime(date2.split(".")[0], date_format) date1_obj = date1_obj.replace(microsecond=0) date2_obj = date2_obj.replace(microsecond=0) return date1 if date1_obj > date2_obj else date2