【问题标题】:How to view MySQL formatted date and time when querying through Python?通过Python查询时如何查看MySQL格式化的日期和时间?
【发布时间】:2017-04-10 02:09:04
【问题描述】:

所以我将我的 Python 文件链接到 MySQL 数据库,并且我想查询几个表中的所有值,其中包括一个 DATE 条目和一个 TIME 条目。现在,当我在 MySQL 中执行此操作时,我会得到如下格式良好的值:2017-07-26, 12:30:00

但是,当我运行查询表的 python 文件时,我得到了这些值:datetime.date(2017, 7, 26), datetime.timedelta(0, 45000))

如何解决这个问题,以便运行 Python 文件以我在 MySQL 中查询时得到的相同格式返回日期和时间值?

【问题讨论】:

  • 请将您的代码粘贴到您的问题中,而不是图片中!
  • 我将输出更新为代码格式

标签: python mysql database


【解决方案1】:

datetime.date(2017, 7, 26) 是表示日期的 Python 对象,datetime.timedelta(0, 45000) 是我们必须添加到日期的持续时间(此处为 0 天 45000 秒)。

Python 表示datetime.datetime 对象中的组合日期和时间。我们根据日期和持续时间创建一个,然后对其进行格式化:

import datetime

date = datetime.date(2017, 7, 26)
delta = datetime.timedelta(0, 45000)

# We convert the date into a datetime object (same date, at midnight)
# and add the delta
date_and_time = datetime.datetime.combine(date, datetime.time()) + delta

mysql_formatted_date = datetime.datetime.strftime(date_and_time, "%Y-%m-%d, %H:%M:%S")

print(mysql_formatted_date)
#2017-07-26, 12:30:00

【讨论】:

    【解决方案2】:

    您可以使用strftimedatetime 对象转换为您喜欢的任何格式。

    例如对于您的情况,您可以使用 -

    value.strftime('%Y-%m-%d, %H:%M:%S')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-08-05
      • 1970-01-01
      • 2011-07-01
      • 1970-01-01
      • 2021-12-12
      • 1970-01-01
      • 2017-11-16
      相关资源
      最近更新 更多