In Python, if I have a unix timestamp, how do I insert that into a MySQL datetime field?
database, date, datetime, mysql, python
Solution
To convert from a UNIX timestamp to a Python datetime object, use `datetime.fromtimestamp()` (documentation).
>>> from datetime import datetime
>>> datetime.fromtimestamp(0)
datetime.datetime(1970, 1, 1, 1, 0)
>>> datetime.fromtimestamp(1268816500)
datetime.datetime(2010, 3, 17, 10, 1, 40)
From Python datetime to UNIX timestamp:
>>> import time
>>> time.mktime(datetime(2010, 3, 17, 10, 1, 40).timetuple())
1268816500.0
Problem
I am using Python MySQLDB, and I want to insert this into DATETIME field in Mysql . How do I do that with cursor.execute?