Get seconds since midnight in Python [closed]
I want to get the seconds that expired since last midnight. What's the most elegant way in Python?
Solution 1:
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?
Solution 2:
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.
Solution 3:
I would do it this way:
import datetime
import time
today = datetime.date.today()
seconds_since_midnight = time.time() - time.mktime(today.timetuple())