How to fix Python error “AttributeError: ‘datetime.datetime’ object has no attribute ‘timestamp'”

Problem:

You want to convert a datetime object into a unix timestamp (int or float: seconds since 1970-1-1 00:00:00) in Python using code like

from datetime import datetime
timestamp = datetime.now().timestamp()

but you see an error message like this:

Traceback (most recent call last):
  File "unix-timestamp.py", line 2, in <module>
    timestamp = datetime.now().timestamp()
AttributeError: 'datetime.datetime' object has no attribute 'timestamp'

Solution:

You are running your code with Python 2.x which does not support datetime.timestamp() – in most cases the easiest way to fix this issue is to use Python 3, e.g.:

python3 unix-timestamp.py

In case that is not possible e.g. due to incompatibilities, use this snippet instead, which is compatible with both Python 2 and Python 3:

from datetime import datetime
import time

dt = datetime.now()
timestamp = time.mktime(dt.timetuple()) + dt.microsecond/1e6