python 在python中将mysql时间戳转换为纪元时间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/115866/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 19:31:12  来源:igfitidea点击:

Convert mysql timestamp to epoch time in python

pythonmysqltimetimestamp

提问by bigredbob

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

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

回答by David Singer

Why not let MySQL do the hard work?

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

select unix_timestamp(fieldname) from tablename;

回答by bigredbob

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

回答by Tony Meyer

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:

如果您出于某种原因不想让 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())

回答by Tom

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?