简体   繁体   English

将MySQL时间戳转换为Python中的纪元时间

[英]Convert mysql timestamp to epoch time in python

在python中将mysql时间戳转换为纪元时间-有没有简单的方法可以做到这一点?

为什么不让MySQL做艰苦的工作呢?

select unix_timestamp(fieldname) from tablename;

converting mysql time to epoch: 将mysql时间转换为纪元:

>>> 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: 将纪元转换为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

If you don't want to have MySQL do the work for some reason, then you can do this in Python easily enough. 如果您由于某种原因不想让MySQL进行工作,那么您可以在Python中足够容易地做到这一点。 When you get a datetime column back from MySQLdb, you get a Python datetime.datetime object. 当您从MySQLdb获取datetime列时,您将获得一个Python datetime.datetime对象。 To convert one of these, you can use time.mktime. 要转换其中之一,可以使用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())

I use something like the following to get seconds since the epoch (UTC) from a MySQL date (local time): 我使用以下类似的方法从MySQL日期(本地时间)起从纪元(UTC)开始获得秒数:

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? 有关此问题的更多信息: 如何在Python中将本地时间转换为UTC?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM