liv2hak
liv2hak

Reputation: 15010

Comparing two timestamp strings in Python

I have JSON file which has timestamps in it.The timestamp in the format shown below.

timestamp1 Fri Mar 27 15:25:24 NZDT 2015

timestamp2 Fri Mar 27 15:23:01 NZDT 2015

Between the above two timestamps above timestamp1 is at a later time than timestamp2.

How can I compare these timestamps in a python program,so that among hundreds of timestamps extracted from a JSON file I get the latest timestamp.I have written the program to extract the timestamp people.I don't know how to compare them.

# Import the os module, for the os.walk function
import os
import json

# Set the directory you want to start from
rootDir = '/Workspace/events_parts'
for dirName, subdirList, fileList in os.walk(rootDir):
    print('Found directory: %s' % dirName)
    for fname in fileList:
        print('\t%s' % fname)
        fname='events_parts/'+fname
        with open(fname, 'r+') as f:
            json_data = json.load(f)
            ts = json_data['Timestamp']
            print(ts)

Upvotes: 1

Views: 7564

Answers (2)

user4700203
user4700203

Reputation:

If New Zealand Daylight time (NZDT) is common for all your data then you can use this method. (Only if NZDT is common)

#for python3
import time

timestamp1 = 'Fri Mar 27 15:25:24 NZDT 2015'
timestamp2 = 'Fri Mar 27 15:23:01 NZDT 2015'

pattern = '%a %b %d %H:%M:%S NZDT %Y'

epoch_timestamp1 = int(time.mktime(time.strptime(timestamp1, pattern)))
epoch_timestamp2 = int(time.mktime(time.strptime(timestamp2, pattern)))


if epoch_timestamp1 > epoch_timestamp2:
  print ("Timestamp1 is the latest")
else:
  print ("Timestamp2 is the latest")

Output

Timestamp1 is the latest

Upvotes: 2

Andy
Andy

Reputation: 50610

You need to convert your timestamp strings into datetime objects. Normally, I'd recommend that you use the strptime. However, you have a timezone in your string (NZDT) and the documentation says:

Support for the %Z directive is based on the values contained in tzname and whether daylight is true. Because of this, it is platform-specific except for recognizing UTC and GMT which are always known (and are considered to be non-daylight savings timezones).

Instead, we'll utilize the python-dateutil package.

pip install python-dateutil

From here, we can utilize the parse function to get a datetime object. With this, you can perform any comparisons you need.

>>> from dateutil.parser import parse
>>> t1 = "Fri Mar 27 15:25:24 NZDT 2015"
>>> t2 = "Fri Mar 27 15:23:01 NZDT 2015"
>>> d1 = parse(t1)
>>> d2 = parse(t2)
>>> d1 > d2
True

Upvotes: 3

Related Questions