Skip to content

Proposal for datetime comparison where precision of the datetimes is different. #1372

@JozefAerts

Description

@JozefAerts

Unfortunately, sometimes, we need to compare datetimes for wich the granularity/precision is different. For example, compare:
datetime1 = 2025-06-25
datetime2 = 2025-06-25T17:22

Therefore I propose a function that allows to compare the "common" part of the two datetimes.
For the above, this means datetime2 is reduced to "2025-06-27" which has the same character length as datetime1. The result of the comparison would then be "equal".
Whereas when datetime2 would be "2025-06-24T16:40:33. the result would be that datetime2 comes before datetime1.

I am pretty bad in Python, so I asked ChatGPT to write such a function for me. The code is below.
So I propose to develop some new operators based on this function, similar to "date_equal_to", "date_greater_than", etc..
I let people with a better knowledge of the English language to come up with appropriate names ...

Python: code (many thanks to ChatGPT ...):

from datetime import datetime

def compare_iso_datetimes(dt1: str, dt2: str) -> int:
"""
Compare two ISO-8601 datetime strings by truncating both to the length
of the shorter string before parsing.

Returns:
    -1 if dt1 < dt2
     0 if dt1 == dt2
     1 if dt1 > dt2
"""
# Truncate both to the length of the shortest string
min_len = min(len(dt1), len(dt2))
dt1_trunc = dt1[:min_len]
dt2_trunc = dt2[:min_len]

# Attempt to parse truncated strings
# Fallback: if parsing fails, compare lexicographically
try:
    d1 = datetime.fromisoformat(dt1_trunc)
    d2 = datetime.fromisoformat(dt2_trunc)
except ValueError:
    # Fall back to lexicographic comparison if parsing fails
    if dt1_trunc < dt2_trunc:
        return -1
    elif dt1_trunc > dt2_trunc:
        return 1
    else:
        return 0

# Compare datetimes
if d1 < d2:
    return -1
elif d1 > d2:
    return 1
else:
    return 0

Metadata

Metadata

Assignees

Labels

SDTMCDISC SDTM/SDTMIGSEND

Type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions