51
votes

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

3
What have you tried to do this? Can you share some code with us? (I'm sure the downvotes are just because of this ...) - Levon
Actually I was searching for that question on stackoverflow but could not get an answer. After consulting the python docs I had a solution I liked. To help other people with the same problem I posted my solution as a question & answer. But apparently people don't like that, even though it gets promoted here blog.stackoverflow.com/2011/07/… - linqu
'closed as not a real question by geoffspear, Levon, gnat, A5C1D2H2I1M1N2O1R2T1, gaige'. I strongly disagree. - EB88
'It's difficult to tell what is being asked here.' It's pretty obvious actually, stop being so pedantic. - EB88
How about timestamp % 86400? - Nour Wolf

3 Answers

54
votes

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?

22
votes
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.

3
votes

I would do it this way:

import datetime
import time

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