Convert mysql timestamp to epoch time in python - is there an easy way to do this?
Asked
Active
Viewed 1.9k times
4 Answers
28
Why not let MySQL do the hard work?
select unix_timestamp(fieldname) from tablename;

Azat Ibrakov
- 9,998
- 9
- 38
- 50

David Singer
- 1,172
- 1
- 10
- 11
9
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
- 1,847
- 4
- 19
- 19
5
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
- 10,079
- 6
- 41
- 47
1
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?