Convert mysql timestamp to epoch time in python

18,615

Solution 1

Why not let MySQL do the hard work?

select unix_timestamp(fieldname) from tablename;

Solution 2

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

Solution 3

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())

Solution 4

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: How do I convert local time to UTC in Python?

Share:
18,615
Admin
Author by

Admin

Updated on June 09, 2022

Comments

  • Admin
    Admin almost 2 years

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