简体   繁体   English

日期格式不正确,有时间

[英]Improper date formatting, with time

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

Why is time added to date?为什么将时间添加到日期? I explicitly define my format without time.我没有时间明确定义我的格式。 How to have date only: 2020-11-13?如何只有日期:2020-11-13?

In your code, date is a datetime object (not a date object), it has attributes hour, minute and second set to zero.在您的代码中, date是日期时间 object(不是日期对象),它的小时、分钟和秒属性设置为零。 if you print it, you effectively call its __str__ method - which returns isoformat with space as separator.如果你print它,你有效地调用了它的__str__方法——它返回以空格作为分隔符的 isoformat。 That's why you get Ymd H:M:S .这就是你得到Ymd H:M:S的原因。

If you want today's date as string, simply use如果你想要今天的日期作为字符串,只需使用

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

The format string you specify in datetime.datetime.strptime() is the format of the string argument you pass to the method, not the output. The return value of the method is datetime.datetime object. Anyway, you can use datetime.date.today() to get datetime.date , ie without time.您在datetime.datetime.strptime()中指定的格式字符串是您传递给该方法的字符串参数的格式,而不是 output。该方法的返回值为datetime.datetime object。无论如何,您可以使用datetime.date.today()得到datetime.date ,即没有时间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM