How to compare two timestamps in Python?
Emily Wong
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 2014How can I calculate how many days or hours are from timestamp1 to timestamp2?
How can I know which timestamp is the latest one?
12 Answers
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 caseYou can get information on datetime.strptime formats here.
First you need to convert those strings into an object on which Python can do calculations. This is done using the strptime method of the datetime module.
import datetime
s1 = 'Feb 12 08:02:32 2015'
s2 = 'Jan 27 11:52:02 2014'
d1 = datetime.datetime.strptime(s1, '%b %d %H:%M:%S %Y')
d2 = datetime.datetime.strptime(s2, '%b %d %H:%M:%S %Y')
print(d1-d2)This will print 380 days, 20:10:30