在python中获取自午夜以来的秒数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15971308/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 21:29:36 来源:igfitidea点击:
Get seconds since midnight in python
提问by linqu
I want to get the seconds that expired since last midnight. What's the most elegant way in python?
我想获取自上次午夜以来过期的秒数。python中最优雅的方式是什么?
采纳答案by eumiro
It is better to make a single call to a function that returns the current date/time:
最好对返回当前日期/时间的函数进行一次调用:
from datetime import datetime
now = datetime.now()
seconds_since_midnight = (now - now.replace(hour=0, minute=0, second=0, microsecond=0)).total_seconds()
Or does
或者做
datetime.now() - datetime.now()
return zero timedelta for anyone here?
为这里的任何人返回零时间增量?
回答by linqu
I would do it that way
我会那样做
import datetime
import time
today = datetime.date.today()
seconds_since_midnight = time.time() - time.mktime(today.timetuple())
回答by Lennart Regebro
import datetime
now = datetime.datetime.now()
midnight = now.replace(hour=0, minute=0, second=0, microsecond=0)
seconds = (now - midnight).seconds
or
或者
import datetime
now = datetime.datetime.now()
midnight = datetime.datetime.combine(now.date(), datetime.time())
seconds = (now - midnight).seconds
Which to choose is a matter of taste.
选择哪个是品味问题。

