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

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

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.

Leave a Comment