How to compare two timestamps in Python?

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?

1

2 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 case 

You can get information on datetime.strptime formats here.

3

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

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like