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 from timestamp1 to timestamp2?

How to find out which timestamp 1 is the last?

Many thanks.

+4
source share
2 answers

You can use datetime.strptimeto convert these lines to datetimeobjects , then get the object timedeltaby simply subtracting them or find the largest value 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 about the formats datetime.strptime here .

+9
source

, Python . strptime datetime.

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)

380 days, 20:10:30

+1

Source: https://habr.com/ru/post/1523879/


All Articles