use*_*621 1 python datetime utc
我的数据有一个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()
Run Code Online (Sandbox Code Playgroud)
谢谢你的帮助.
要将字符串转换为datetime对象,只需使用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)
Run Code Online (Sandbox Code Playgroud)
要将当前时间作为"自纪元以来的秒数",请使用time.time():
#!/usr/bin/env python
import time
now = time.time()
then = int('1426402510')
print("Duration: %.0f seconds" % (now - then))
Run Code Online (Sandbox Code Playgroud)
如果您需要使用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)
Run Code Online (Sandbox Code Playgroud)
你可以timedelta.total_seconds()在Python 2上使用哪里/ timedelta不起作用.
| 归档时间: |
|
| 查看次数: |
4736 次 |
| 最近记录: |