python - 日期格式不正确,有时间
问题描述
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?
解决方案
在您的代码中,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
推荐阅读
- python - numpy.ufunc.outer 中的轴
- javascript - Javascript - 如何将字符串'0'转换为数字0
- oracle - 使用 Oracle 更改具有较高日期的所有重复项的字段值
- javascript - Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0 only on get request page
- php - 在 JOIN 中获取完全相同的列时出现问题
- sql - Oracle SQL如何消除特定列的重复行
- javascript - 使用 Vue CLI 在 Node js 上进行 Express Session
- c++ - * 类型的参数与 * 类型的参数不兼容
- node.js - Discord.JS - 如何有条件地在嵌入中设置字段?
- batch-file - 如何使用 CMD 在变量中写入可移动设备的字母?