I have a bunch of datetime objects and I want to calculate the number of seconds since a fixed time in the past for each one (for example since January 1, 1970).
import datetime
t = datetime.datetime(2009, 10, 21, 0, 0)
This seems to be only differentiating between dates that have different days:
t.toordinal()
How does one convert a datetime
object to seconds?
Best Answer
For the special date of January 1, 1970 there are multiple options.
For any other starting date you need to get the difference between the two dates in seconds. Subtracting two dates gives a
timedelta
object, which as of Python 2.7 has atotal_seconds()
function.The starting date is usually specified in UTC, so for proper results the
datetime
you feed into this formula should be in UTC as well. If yourdatetime
isn't in UTC already, you'll need to convert it before you use it, or attach atzinfo
class that has the proper offset.As noted in the comments, if you have a
tzinfo
attached to yourdatetime
then you'll need one on the starting date as well or the subtraction will fail; for the example above I would addtzinfo=pytz.utc
if using Python 2 ortzinfo=timezone.utc
if using Python 3.