MySQL Datetime string to a Timestamp

Here is a simple function to convert a datetime string from MySQL to a UNIX timestamp using Python.

import time
# Converts an SQL datetime to a UNIX timestamp
# Example datetime: 2007-04-15 08:29:39
def sqlDateTimeToTimeStamp(sqlDateTime):
return int(time.mktime(time.strptime\
(sqlDateTime,\
“%Y-%m-%d %H:%M:%S”)))

2 Responses to “MySQL Datetime string to a Timestamp”

  1. Olivio Moura Says:

    from time import strptime, strftime

    olddate = ‘05:26:40 Jun 19, 2007 PST’
    newdate = strptime(” “.join(olddate.split()[:-1]), “%H:%M:%S %b %d, %Y”)
    print newdate
    mysqldate = strftime(”%Y-%m-%d %H:%M:%S”, newdate)
    print mysqldate

  2. axdkcd Says:

    thanks a ton. these gems save us so much time!

Leave a Reply