Reputation: 26333
time.time() gives current time in seconds from a given reference. Is there a mean to convert a date to a number of seconds since given reference?
I thought of calendar.timegm(), but I am not sure how to format the argument.
thanks!
Upvotes: 0
Views: 169
Reputation: 213015
calendar.timegm
is the good approach. Just pass it the utctimetuple()
output from your datetime object:
from datetime import datetime
import pytz
import calendar
dt = datetime.now(pytz.utc)
secs = calendar.timegm(dt.utctimetuple())
print dt, secs
prints
2012-03-09 09:17:14.698500+00:00 1331284634
just to test it against the epoch:
print calendar.timegm(datetime(1970, 1, 1, 0, 0, 0, tzinfo=pytz.utc).utctimetuple())
prints 0
.
Upvotes: 1
Reputation: 17036
It sounds like you have current time X (seconds since the epoch), and you have a reference time Y. You want the number of seconds between them.
Use mktime
to get seconds from the epoch to your reference point, and then just subtract X from Y, or Y from X (depending on which order you want).
Upvotes: 2