Get seconds since midnight in Python

PythonDateDatetime

Python Problem Overview


I want to get the seconds that expired since last midnight. What's the most elegant way in Python?

Python Solutions


Solution 1 - 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?

Solution 2 - Python

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 - Python

I would do it this way:

import datetime
import time

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionlinquView Question on Stackoverflow
Solution 1 - PythoneumiroView Answer on Stackoverflow
Solution 2 - PythonLennart RegebroView Answer on Stackoverflow
Solution 3 - PythonlinquView Answer on Stackoverflow