'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 1:[1]

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.')

Solution 2:[2]

This format has milliseconds in it, so it cannot be parsed by time.strptime. I chose to split according to the last colon, parse the left part, and manually convert the right part, add them together.

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

import time

def parse_date(s):
    date,millis = s.rsplit(":",1)
    return time.mktime(time.strptime(date,"%Y-%m-%d %H:%M:%S")) + int(millis)/1000.0

print(parse_date(A))
print(parse_date(B))

prints:

1549958505.145
1549958522.022

now compare the results instead of printing them to get what you want

If your convention on milliseconds is different (ex: here 22 could also mean 220), then it's slightly different. Pad with zeroes on the right, then parse:

def parse_date(s):
    date,millis = s.rsplit(":",1)
    millis = millis+"0"*(3-len(millis))   # pad with zeroes
    return time.mktime(time.strptime(date,"%Y-%m-%d %H:%M:%S")) + int(millis)/1000.0

in that case the result it:

1549958505.145
1549958522.22

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Jean-François Fabre