首页 > 解决方案 > 日期格式不正确,有时间

问题描述

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?

标签: pythonpython-3.xdatetime

解决方案


在您的代码中,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

推荐阅读