【问题标题】:Improper date formatting, with time日期格式不正确,有时间
【发布时间】:2020-11-13 15:58:23
【问题描述】:
now = datetime.datetime.now()
today = str(now.year) + '-' + str(now.month) + '-' + str(now.day)
date = datetime.datetime.strptime(today, "%Y-%m-%d")
print(date) # 2020-11-13 00:00:00

为什么要将时间添加到日期中?我没有时间明确定义我的格式。 如何只有日期:2020-11-13?

【问题讨论】:

  • 因为它是 datetime.datetime 对象,而不是 datetime.date。而这一切的目的是什么?为什么不只是datetime.date.today()?请注意,您指定的是输入格式,而不是输出。输出为datetime.datetime对象
  • 确实,请将此作为答案发布,我会接受。

标签: python python-3.x datetime


【解决方案1】:

在您的代码中,date 是一个日期时间对象(不是日期对象),它的小时、分钟和秒属性设置为零。如果你print 它,你实际上调用了它的__str__ 方法——它返回以空格作为分隔符的isoformat。这就是你得到Y-m-d H:M:S的原因。

如果要将今天的日期作为字符串,只需使用

from datetime import date
print(date.today())
# or
print(date.today().strftime("%Y-%m-%d")) # same as date.today().isoformat()
# or even
from datetime import datetime
print(datetime.today().strftime("%Y-%m-%d"))

# all print to 
# 2020-11-13

【讨论】:

    【解决方案2】:

    您在datetime.datetime.strptime() 中指定的格式字符串是您传递给方法的字符串参数的格式,而不是输出。该方法的返回值为datetime.datetime 对象。不管怎样,你可以用datetime.date.today()得到datetime.date,即没有时间。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-29
      • 2017-07-18
      相关资源
      最近更新 更多