xvienxz2
xvienxz2

Reputation: 63

comparing 2 timestamp in python json

[{"id":360015384872,"action":"article_created","timestamp":"2018-06-26T05:43:05Z","breadcrumbs"]

lets say i have timestamp: 2018-06-26T05:43:05Z

and another timestamp2: 2018-06-26T05:43:55Z - this one is more current by 50 seconds

i want to make it so that if timestamp2 > timestamp1 (meaning timestamp2 is the latest time or more current), print (timestamp2)

how can i do that in python json? i know how i would do this if it was integers which is timestamp2 > timestamp1.. but seem more difficult with timestamp

Upvotes: 0

Views: 2059

Answers (2)

Rakesh
Rakesh

Reputation: 82785

You can convert string to datetime object using datetime module and then compare.

Ex:

import datetime
t1 = "2018-06-26T05:43:05Z"
t2 = "2018-06-26T05:43:55Z"
t1 = datetime.datetime.strptime(t1, "%Y-%m-%dT%H:%M:%SZ")
t2 = datetime.datetime.strptime(t2, "%Y-%m-%dT%H:%M:%SZ")

if t2 > t1:
    print(t2)

Output:

2018-06-26 05:43:55

Upvotes: 1

Sunitha
Sunitha

Reputation: 12015

You can convert these date strings to datetime object and then just comparse them easily. I would suggest dateutil.parser for parsing these date strings easily. You can get it by doing pip install python-dateutil

from dateutil import parser
t1 = parser.parse("2018-06-26T05:43:05Z")
t2 = parser.parse("2018-06-26T05:43:55Z")

t1 > t2
# False

t1 < t2
# True

Upvotes: 0

Related Questions