vitaliis
vitaliis

Reputation: 4212

How to define a difference in time in seconds between a timestamp saved as a string and a current UTC timestamp

I am testing the difference between an actual UTC time and timestamp when my object was saved in a table (UTC). It must be not more than 60 seconds. Example of timestamp_from_table (string from my site): 2021-02-05 13:51:52

After researching for options to make this, I came to this approach:

timestamp_from_table = driver.find_element_by_css_selector("my_locator").text
current_time = time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime())  # current time converted to string
current_time_truncated = datetime.strptime(current_time, "%Y-%m-%d %H:%M:%S")  # cutting milliseconds
date_time_obj = datetime.strptime(timestamp_from_table, '%Y-%m-%d %H:%M:%S')  # converting string timestamp to a datetime object
time_difference = current_time_truncated - date_time_obj
result = time_difference.seconds # datetime.timedelta represented in seconds
assert result in range(1, 60), error()

It works just fine, but probably there is a shorter way to compare a difference between a timestamp saved as string and actual utc timestamp. Thanks for any advice.

Upvotes: 1

Views: 194

Answers (1)

rhurwitz
rhurwitz

Reputation: 2747

I'm reading between the lines a bit, but it sounds like at a high level your goal is to calculate the elapsed seconds between two times. If I'm right about that, here is a typical way to do it in Python:

import datetime
import time

previous = datetime.datetime.now()
time.sleep(5) # Added to simulate the passing of time for demonstration purposes
current = datetime.datetime.now()

elapsed_seconds = (current - previous) / datetime.timedelta(seconds=1)

"Division" by timedelta is the key to getting elapsed seconds (or any other time unit) between two datetime objects. While not UTC specific hopefully this shines a light on an approach that works for you.

Upvotes: 1

Related Questions