2015-10-15 36 views
1

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

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

感谢您的帮助。

回答

6

要将字符串转换为日期时间对象,只需在您的时间戳字符串上使用utcfromtimestamp调用int即可。

import datetime 

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

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

print(diff) 
6

为了得到当前时间 “秒从纪元”,用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中使用timedelta.total_seconds() 2其中/ timedelta不起作用。