In Python, how do you convert a `datetime` object to seconds?

Nathan Lippi picture Nathan Lippi · Oct 21, 2011 · Viewed 431.1k times · Source

Apologies for the simple question... I'm new to Python... I have searched around and nothing seems to be working.

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()

Any help is much appreciated.

Answer

Mark Ransom picture Mark Ransom · Oct 21, 2011

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 a total_seconds() function.

>>> (t-datetime.datetime(1970,1,1)).total_seconds()
1256083200.0

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 your datetime isn't in UTC already, you'll need to convert it before you use it, or attach a tzinfo class that has the proper offset.

As noted in the comments, if you have a tzinfo attached to your datetime then you'll need one on the starting date as well or the subtraction will fail; for the example above I would add tzinfo=pytz.utc if using Python 2 or tzinfo=timezone.utc if using Python 3.