Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 468
Max Avatar asked Jan 27 '14 10:01

Max


People also ask

Can we compare two timestamps in Python?

And, it is required to compare timestamps to know the latest entry, entries between two timestamps, the oldest entry, etc. for various tasks. Comparison between pandas timestamp objects is carried out using simple comparison operators: >, <,==,< = , >=. The difference can be calculated using a simple '–' operator.

How do I compare two datetime values in Python?

Use datetime. date() to compare two dates Call datetime. date(year, month, day) twice to create two datetime. date objects representing the dates of year , month , and day . Use the built-in comparison operators (e.g. < , > , == ) to compare them.

How do you compare timestamps?

When comparing two TIMESTAMP WITH TIME ZONE values, the comparison is made using the UTC representations of the values. Two TIMESTAMP WITH TIME ZONE values are considered equal if they represent the same instance in UTC, regardless of the time zone offsets that are stored in the values. For example, '1999-04-15-08.00.

Can you compare datetime Python?

When you have two datetime objects, the date and time one of them represent could be earlier or latest than that of other, or equal. To compare datetime objects, you can use comparison operators like greater than, less than or equal to.


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.

like image 106
jonrsharpe Avatar answered Sep 22 '22 05:09

jonrsharpe


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

like image 26
Burhan Khalid Avatar answered Sep 22 '22 05:09

Burhan Khalid