Skip to main content
 首页 » 编程设计

python之比较 Python 中的两个 UTC 时间戳

2025年05月04日8JustinYoung

我的数据有一个字符串格式的 UTC 时间戳字段(例如“1426402510”)。我需要将此字段与当前时间进行比较,并以秒为单位发出持续时间。我不确定如何将此字符串转换为正确的日期时间格式以进行转换 - 我尝试在 Python 中使用不同的日期时间方法产生了错误,因此非常感谢您的帮助。这是我的部分代码:

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

感谢您的帮助。

请您参考如下方法:

要获取当前时间“自纪元以来的秒数”,请使用 time.time() :

#!/usr/bin/env python 
import time 
 
now = time.time() 
then = int('1426402510') 
print("Duration: %.0f seconds" % (now - then)) 

如果需要使用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) 

您可以在 Python 2 上使用 timedelta.total_seconds(),其中 /timedelta 不起作用。