我的数据有一个UTC时间戳字段作为字符串格式(例如' 1426402510')。我需要将此字段与当前时间进行比较,并以秒为单位发出持续时间。我不确定如何将此字符串转换为正确的日期时间格式进行转换 - 我在Python中使用不同的datetime方法的尝试产生了错误,所以我将非常感谢您的帮助。这是我的代码的一部分:
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()
感谢您的帮助。
答案 0 :(得分: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)
答案 1 :(得分: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 {2}上使用timedelta.total_seconds()
,/ timedelta
不起作用。