views:

4563

answers:

4

Convert mysql timestamp to epoch time in python - is there an easy way to do this?

+9  A: 

Why not let MySQL do the hard work?

select unix_timestamp(fieldname) from tablename;

David Singer
+2  A: 

If you don't want to have MySQL do the work for some reason, then you can do this in Python easily enough. When you get a datetime column back from MySQLdb, you get a Python datetime.datetime object. To convert one of these, you can use time.mktime. For example:

import time
# Connecting to database skipped (also closing connection later)
c.execute("SELECT my_datetime_field FROM my_table")
d = c.fetchone()[0]
print time.mktime(d.timetuple())
Tony Meyer
+1  A: 

I use something like the following to get seconds since the epoch (UTC) from a MySQL date (local time):

calendar.timegm(
   time.gmtime(
      time.mktime(
         time.strptime(t, 
                       "%Y-%m-%d %H:%M:%S"))))

More info in this question: http://stackoverflow.com/questions/79797/how-do-i-convert-local-time-to-utc-in-python

Tom
+1  A: 

converting mysql time to epoch:

>>> import time
>>> import calendar
>>> mysql_time = "2010-01-02 03:04:05"
>>> mysql_time_struct = time.strptime(mysql_time, '%Y-%m-%d %H:%M:%S')
>>> print mysql_time_struct
(2010, 1, 2, 3, 4, 5, 5, 2, -1)
>>> mysql_time_epoch = calendar.timegm(mysql_time_struct)
>>> print mysql_time_epoch
1262401445

converting epoch to something MySQL can use:

>>> import time
>>> time_epoch = time.time()
>>> print time_epoch
1268121070.7
>>> time_struct = time.gmtime(time_epoch)
>>> print time_struct
(2010, 3, 9, 7, 51, 10, 1, 68, 0)
>>> time_formatted = time.strftime('%Y-%m-%d %H:%M:%S', time_struct)
>>> print time_formatted
2010-03-09 07:51:10
bigredbob