我想获得自上个午夜以来过期的秒数。Python中最优雅的方式是什么?
问问题
46839 次
3 回答
57
最好对返回当前日期/时间的函数进行一次调用:
from datetime import datetime
now = datetime.now()
seconds_since_midnight = (now - now.replace(hour=0, minute=0, second=0, microsecond=0)).total_seconds()
或者确实
datetime.now() - datetime.now()
为这里的任何人返回零时间增量?
于 2013-04-12T12:31:41.847 回答
24
import datetime
now = datetime.datetime.now()
midnight = now.replace(hour=0, minute=0, second=0, microsecond=0)
seconds = (now - midnight).seconds
或者
import datetime
now = datetime.datetime.now()
midnight = datetime.datetime.combine(now.date(), datetime.time())
seconds = (now - midnight).seconds
选择哪个是口味问题。
于 2013-04-12T12:30:55.263 回答
4
我会这样做:
import datetime
import time
today = datetime.date.today()
seconds_since_midnight = time.time() - time.mktime(today.timetuple())
于 2013-04-12T12:22:43.720 回答