user2327621
user2327621

Reputation: 997

compare two UTC timestamps in Python

My data has a UTC timestamp field as a string format(e.g '1426402510'). I need to compare this field to the current time and emit the duration in seconds. I am not sure how to convert this string into a proper datetime format for conversion - my attempts at using the different datetime methods in Python yielded errors, so I would appreciate your help. Here is a portion of my code:

 import datetime

 # get current local time as a UTC timestamp
 current_time = datetime.datetime.utcnow()
 current_time.strftime("%s")

 # convert the string representing the UTC timestamp in my data to datetime for comparison
 time_val = '1426402510'
 #utc_dt = ??      # how should I convert time_val to compare with current_time?

 # the required output
 diff = (current_time - utc_dt).total_seconds()

thanks for your help.

Upvotes: 1

Views: 13621

Answers (2)

Padraic Cunningham
Padraic Cunningham

Reputation: 180411

To convert the string to a datetime object, you just need to use utcfromtimestamp calling int on your timestamp string.

import datetime

current_time = datetime.datetime.utcnow()
time_val = '1426402510'

diff = (current_time - datetime.datetime.utcfromtimestamp(int(time_val))).total_seconds()

print(diff)

Upvotes: 6

jfs
jfs

Reputation: 414215

To get the current time as "seconds since the epoch", use time.time():

#!/usr/bin/env python
import time

now = time.time()
then = int('1426402510')
print("Duration: %.0f seconds" % (now - then))

If you need to use datetime:

#!/usr/bin/env python3
from datetime import datetime, timedelta

now = datetime.utcnow()
then = datetime.utcfromtimestamp(int('1426402510'))
diff = (now - then) / timedelta(seconds=1)
print("Duration: %.0f seconds" % diff)

You could use timedelta.total_seconds() on Python 2 where / timedelta doesn't work.

Upvotes: 6

Related Questions