【问题标题】:Print dates in Python在 Python 中打印日期
【发布时间】:2017-06-09 11:59:41
【问题描述】:

如果我在 MYSQL 表中打印列的日期,我会看到:

(datetime.date(2017,5,26),)

但我想要这个:

2017-05-26

这是我的代码:

connection=...
cursor = connection.cursor()
sqlQuery = "SELECT DISTINCT timestamp FROM table "
sqlCommand = sqlQuery.format()
cursor.execute(sqlCommand)
cursor.close()
connection.close()

我使用 Python。

有人可以帮我吗?

【问题讨论】:

  • 使用日期时间yourdate.strftime("%Y-%m-%d")怎么样?
  • 倒是time.strftime("%Y-%m-%d", your_date)
  • 我用这个:datetime.date.today()
  • 然后改成datetime.datetime.today().strftime("%Y-%m-%d")

标签: python mysql datetime


【解决方案1】:

假设你的日期在mydate:

在 Python 3.6 中:

print (f"{mydate:%Y-%m-%d}")

在早期版本中:

print (mydate.strftime("%Y-%m-%d"))

【讨论】:

    【解决方案2】:

    只需使用str():

    >>> str(datetime.date(2017, 5, 26))
    '2017-05-26'
    

    这与在日期实例上调用 .isoformat() 相同。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-09
      • 2021-06-11
      • 2017-04-24
      • 1970-01-01
      • 1970-01-01
      • 2015-09-24
      • 2014-08-01
      • 2011-08-29
      相关资源
      最近更新 更多