Get seconds since midnight in Python

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?


I would do it this way:

import datetime
import time

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

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.