Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Python, if I have a unix timestamp, how do I insert that into a MySQL datetime field?

I am using Python MySQLDB, and I want to insert this into DATETIME field in Mysql . How do I do that with cursor.execute?

like image 898
TIMEX Avatar asked Mar 17 '10 07:03

TIMEX


People also ask

How does Unix handle timestamp in python?

In the time module, the timegm function returns a Unix timestamp. The timetuple() function of the datetime class returns the datetime's properties as a named tuple. To obtain the Unix timestamp, use print(UTC).

What is Unix timestamp in MySQL?

UNIX_TIMESTAMP() function in MySQL We can define a Unix timestamp as the number of seconds that have passed since '1970-01-01 00:00:00'UTC. Even if you pass the current date/time or another specified date/time, the function will return a Unix timestamp based on that. Parameters : It will accept only one argument.


1 Answers

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
like image 129
codeape Avatar answered Nov 01 '22 17:11

codeape