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?
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.
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With