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
3 points

That looks like ISO8601 format so you can use fromisoformat to make the parsing a bit simpler. I’m not clear why you need to drop the microsecond part. Surely if one timestamp is a few microseconds past the second it is later.

d1 = datetime.fromisoformat(date1)
d2 = datetime.fromisoformat(date2)

return date1 if d1 > d2 else date2
permalink
report
reply
2 points
*

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.

permalink
report
reply
1 point

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

permalink
report
parent
reply

Python

!python@programming.dev

Create post

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

📅 Events
Past

November 2023

October 2023

July 2023

August 2023

September 2023

🐍 Python project:
💓 Python Community:
✨ Python Ecosystem:
🌌 Fediverse
Communities
Projects
  • Pythörhead: a Python library for interacting with Lemmy
  • Plemmy: a Python package for accessing the Lemmy API
  • pylemmy pylemmy enables simple access to Lemmy’s API with Python
  • mastodon.py, a Python wrapper for the Mastodon API
Feeds

Community stats

  • 205

    Monthly active users

  • 463

    Posts

  • 2.4K

    Comments