如何定义保存为字符串的时间戳与当前 UTC 时间戳之间的时间差(以秒为单位)

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

当我的对象保存在 table (UTC) 中时,我正在测试实际 UTC 时间和时间戳之间的差异。不得超过 60 秒。 timestamp_from_table 的示例(来自我网站的字符串):2021-02-05 13:51:52

在研究了制作这个的选项之后,我想到了这个方法:

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()

它工作得很好,但可能有一种更短的方法来比较保存为字符串的时间戳和实际的 utc 时间戳之间的差异。感谢您的任何建议。

我从字里行间看出了一点,但听起来您的目标是计算两次之间经过的秒数。如果我是对的,这是 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)

timedelta 的“除法”是获得两个 datetime 对象之间经过的秒数(或任何其他时间单位)的关键。虽然不是特定于 UTC,但希望这能为您提供一种适合您的方法。