在Python中将MySQL时间戳转换为Epoch时间

7

如何在Python中将MySQL时间戳转换为纪元时间?有简单的方法吗?


MySQL时间戳长什么样? - Corey Goldberg
一个以“YYYY-MM-DD HH:MM:SS”格式表示的字符串。 - Tom
4个回答

28

为什么不让MySQL来做繁重的工作呢?

select unix_timestamp(fieldname) from tablename;

9

将MySQL时间转换为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

将时间戳转换为MySQL可用的格式:

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

5

如果出于某种原因您不想让MySQL来处理,那么您可以很容易地在Python中完成此操作。当您从MySQLdb获得一个datetime列时,您会得到一个Python datetime.datetime对象。要转换其中的一个对象,您可以使用time.mktime。例如:

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

1
我使用类似以下的代码从MySQL日期(本地时间)获取自纪元以来的秒数(UTC):
calendar.timegm(
   time.gmtime(
      time.mktime(
         time.strptime(t, 
                       "%Y-%m-%d %H:%M:%S"))))

这个问题中有更多信息:如何在Python中将本地时间转换为UTC?


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接