如何在Python中找到“自UTC时区开始以来的秒数?我看了看文档,却不明白如何使用datetime.timedelta
来获得它。
这里是一种方法。
from datetime import datetime, time
utcnow = datetime.utcnow()
midnight_utc = datetime.combine(utcnow.date(), time(0))
delta = utcnow - midnight_utc
print delta.seconds # <-- careful
EDIT如建议的那样,如果要微秒精度或可能跨越24小时周期(即delta.days> 0),请使用total_seconds()
或@unutbu给出的公式。
print delta.total_seconds() # 2.7
print delta.days * 24 * 60 * 60 + delta.seconds + delta.microseconds / 1e6 # < 2.7
datetime.timedelta
x
中的秒数由timedelta.total_seconds给出:
x.total_seconds()
此功能在Python2.7中引入。对于旧版本的python,您只需要自己计算即可:total_seconds = x.days*24*60*60 + x.seconds + x.microseconds/1e6
。
import time
t = time.gmtime()
seconds_since_utc_midnight = t.tm_sec + (t.tm_min * 60) + (t.tm_hour * 3600)
对于本地时间,我们可以使用time.localtime()
代替time.gmtime()