this post was submitted on 21 Jul 2023
11 points (100.0% liked)

Python

6343 readers
3 users here now

Welcome to the Python community on the programming.dev Lemmy instance!

๐Ÿ“… Events

PastNovember 2023

October 2023

July 2023

August 2023

September 2023

๐Ÿ Python project:
๐Ÿ’“ Python Community:
โœจ Python Ecosystem:
๐ŸŒŒ Fediverse
Communities
Projects
Feeds

founded 1 year ago
MODERATORS
 

I'm getting errors with this function:

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?

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
you are viewing a single comment's thread
view the rest of the comments
[โ€“] const_void@lemmy.world 2 points 1 year ago* (last edited 1 year ago) (1 children)

if you are reasonably confident your input dates match your format, you could just return date1 if date1>date2 else date2 and call it a day.

[โ€“] celliern@lemmy.world 1 points 1 year ago

Second this : this is a strong benefit of using ISO8601 format as you do : you can use alpha-numeric sort directly.