How to Convert Python DateTime Object to UNIX Timestamp

We will convert a Python datetime object to UNIX timestamp. Before coming to the actual solution which worked, I would like to discuss few other solutions I tried which didn’t work. Now you can ask why don’t you go to the actual solution right away? The thing is that other two solutions work in most of the cases. But depending on the underlying platform library that Python uses, these two approaches might fail. So in some OS environments these solutions might not work for some specific dates & time zones. I tried them & thought they were working, But I encountered bugs in some corner scenarios. So personally I feel these two approaches should be avoided.

Solution 1 (not recommended):

datetime.strftime('%s') returns a string in UNIX timestamp format.
>>> from datetime import datetime
>>> date = datetime(2023, 12, 10)
>>> date.strftime('%s')
'1702146600'

It works well. But it failed in my docker environment which was using some Alpine Linux version. I tried to convert 31st midnight 2023 (Sydney timezone) to UTC timestamp there & it returned -1. But the same date worked fine in my Ubuntu box. I can’t rely on that. I had to find alternate solution.

Solution 2 (not recommended):

>>> import time
>>> from datetime import datetime
>>> date = datetime(2023, 12, 10)
>>> time.mktime(date.timetuple())
1702146600.0

I got “OverflowError: mktime argument out of range” error message this time in my docker environment. Again I started looking for alternate solution.

The first solution depends on strftime function of underlying C library that Python uses. The second solution depends on mktime function of underlying C library that Python uses. Depending on the C library used in different operating systems, I got issues in the result in few cases.

Solution 3 (recommended):

Al last I found a solution which works well in all environments. At least I didn’t find any issue for our use cases. Solution is simple. I just created one extra datetime object to represent epoch time & take a diff of the two datetime objects.

>>> from datetime import datetime
>>> date = datetime(2023, 12, 10)
>>> epoch = datetime(1970, 1, 1)
>>> diff = date - epoch
>>> print(diff.total_seconds())
1702166400.0

Leave a Comment