12

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.

dreftymac
  • 31,404
  • 26
  • 119
  • 182
daydreamer
  • 87,243
  • 191
  • 450
  • 722

3 Answers3

10

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
Joe Holloway
  • 28,320
  • 15
  • 82
  • 92
  • use [`delta.total_seconds()`](http://stackoverflow.com/questions/8072740/pythonnumber-of-seconds-since-the-beginning-of-the-day-utc-timezone/8072776#8072776) – jfs Nov 09 '11 at 22:57
  • If he/she knows it's < 24 hours since the beginning of the day, it's safe to use `timedelta.seconds` correct? Just wondering if there's another reason to avoid it for this answer. – Joe Holloway Nov 09 '11 at 23:20
  • [Leap seconds](https://en.wikipedia.org/wiki/Leap_second) are not supported so it is safe to assume that `delta.days` is `0`. But `.total_seconds()` is better semantically and it is a less burden for a reader of the code. – jfs Nov 09 '11 at 23:44
7

The number of seconds in a datetime.timedelta, x, is given by timedelta.total_seconds:

x.total_seconds()

This function was introduced in Python2.7. For older versions of python, you just have to compute it yourself: total_seconds = x.days*24*60*60 + x.seconds + x.microseconds/1e6.

jfs
  • 399,953
  • 195
  • 994
  • 1,670
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
0
import time
t = time.gmtime()
seconds_since_utc_midnight = t.tm_sec + (t.tm_min * 60) + (t.tm_hour * 3600)

for localtime, we can use time.localtime() instead of time.gmtime()

sonofusion82
  • 200
  • 3