Search code examples
pythonutctimedeltaseconds

Number of seconds since the beginning of the day UTC timezone


How do I find "number of seconds since the beginning of the day UTC timezone" in Python? I looked at the docs and didn't understand how to get this using datetime.timedelta.


Solution

  • Here's one way to do it.

    from datetime import datetime, time
    
    utcnow = datetime.utcnow()
    midnight_utc = datetime.combine(utcnow.date(), time(0))
    delta = utcnow - midnight_utc
    print delta.seconds # <-- careful
    

    EDIT As suggested, if you want microsecond precision, or potentially crossing a 24-hour period (i.e. delta.days > 0), use total_seconds() or the formula given by @unutbu.

    print delta.total_seconds()  # 2.7
    print delta.days * 24 * 60 * 60 + delta.seconds + delta.microseconds / 1e6 # < 2.7