关于日期:在python中从午夜开始获取秒数

Get seconds since midnight in python

我想知道从上个午夜开始的秒数。Python最优雅的方式是什么?


最好对返回当前日期/时间的函数进行单个调用:

1
2
3
4
from datetime import datetime

now = datetime.now()
seconds_since_midnight = (now - now.replace(hour=0, minute=0, second=0, microsecond=0)).total_seconds()

或者是

1
datetime.now() - datetime.now()

为这里的任何人返回零时间增量?


1
2
3
4
import datetime
now = datetime.datetime.now()
midnight = now.replace(hour=0, minute=0, second=0, microsecond=0)
seconds = (now - midnight).seconds

1
2
3
4
import datetime
now = datetime.datetime.now()
midnight = datetime.datetime.combine(now.date(), datetime.time())
seconds = (now - midnight).seconds

选择哪个是一个品味问题。


我会那样做的

1
2
3
4
5
import datetime
import time

today = datetime.date.today()
seconds_since_midnight = time.time() - time.mktime(today.timetuple())


另一种选择:

1
2
from datetime import datetime
seconds = (datetime.now() - datetime.today()).seconds