pythondatedatetime

Get seconds since midnight in Python


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


Solution

  • 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?