How to compare two timestamps in Python?

datetime, python-2.7

Solution

You can use `datetime.strptime` to convert those strings into `datetime` objects, then get a `timedelta` object by simply subtracting them or find the largest using `max`:

from datetime import datetime

timestamp1 = "Feb 12 08:02:32 2015"
timestamp2 = "Jan 27 11:52:02 2014"

t1 = datetime.strptime(timestamp1, "%b %d %H:%M:%S %Y")
t2 = datetime.strptime(timestamp2, "%b %d %H:%M:%S %Y")

difference = t1 - t2

print(difference.days) # 380, in this case

latest = max((t1, t2)) # t1, in this case

You can get information on `datetime.strptime` formats here.

Problem

I am new to Python and I need to know how to compare timestamps. I have the following example: ``` timestamp1: Feb 12 08:02:32 2015 timestamp2: Jan 27 11:52:02 2014 ``` How can I calculate how many days or hours are from `timestamp1` to `timestamp2`? How can I know which timestamp is the latest one?

Original source