Number of seconds since the beginning of the day UTC timezone

点点圈 提交于 2019-12-06 20:58:05

问题


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.


回答1:


Here's one way to do it.

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



回答2:


The number of seconds in a datetime.timedelta, x, is given by timedelta.total_seconds:

x.total_seconds()

This function was introduced in Python2.7. For older versions of python, you just have to compute it yourself: total_seconds = x.days*24*60*60 + x.seconds + x.microseconds/1e6.




回答3:


import time
t = time.gmtime()
seconds_since_utc_midnight = t.tm_sec + (t.tm_min * 60) + (t.tm_hour * 3600)

for localtime, we can use time.localtime() instead of time.gmtime()



来源:https://stackoverflow.com/questions/8072740/number-of-seconds-since-the-beginning-of-the-day-utc-timezone

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!