自一天UTC时区开始以来的秒数 [英] Number of seconds since the beginning of the day UTC timezone

查看:157
本文介绍了自一天UTC时区开始以来的秒数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Python中找到自UTC时区开始以来的秒数"?我看了看文档,却不明白如何使用datetime.timedelta来获得它.

How do I find "number of seconds since the beginning of the day UTC timezone" in Python? I looked at the docs and didn't understand how to get this using 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

编辑如建议的那样,如果要微秒精度或可能跨越24小时周期(即delta.days> 0),请使用total_seconds()或@unutbu给出的公式.

EDIT As suggested, if you want microsecond precision, or potentially crossing a 24-hour period (i.e. delta.days > 0), use total_seconds() or the formula given by @unutbu.

print delta.total_seconds()  # 2.7
print delta.days * 24 * 60 * 60 + delta.seconds + delta.microseconds / 1e6 # < 2.7

这篇关于自一天UTC时区开始以来的秒数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆