pythonpython-datetimedatetime-comparison

Comparing two datetime strings


I have two DateTime strings. How would I compare them and tell which comes first?

A = '2019-02-12 15:01:45:145'
B = '2019-02-12 15:02:02:22'

Solution

  • If both the date/time strings are in ISO 8601 format (YYYY-MM-DD hh:mm:ss) you can compare them with a simple string compare, like this:

    a = '2019-02-12 15:01:45.145'
    b = '2019-02-12 15:02:02.022'
    
    if a < b:
        print('Time a comes before b.')
    else:
        print('Time a does not come before b.')
    

    Your strings, however, have an extra ':' after which come... milliseconds? I'm not sure. But if you convert them to a standard hh:mm:ss.xxx... form, then your date strings will be naturally comparable.


    If there is no way to change the fact that you're receiving those strings in hh:mm:ss:xx format (I'm assuming that xx is milliseconds, but only you can say for sure), then you can "munge" the string slightly by parsing out the final ":xx" and re-attaching it as ".xxx", like this:

    def mungeTimeString(timeString):
        """Converts a time string in "YYYY-MM-DD hh:mm:ss:xx" format
           to a time string in "YYYY-MM-DD hh:mm:ss.xxx" format."""
        head, _, tail = timeString.rpartition(':')
        return '{}.{:03d}'.format(head, int(tail))
    

    Then call it with:

    a = '2019-02-12 15:01:45:145'
    b = '2019-02-12 15:02:02:22'
    
    a = mungeTimeString(a)
    b = mungeTimeString(b)
    
    if a < b:
        print('Time a comes before b.')
    else:
        print('Time a does not come before b.')