python - 显示没有时间的 Python 日期时间

标签 python datetime strptime

我有一个日期字符串,想把它转换成日期类型:

我已尝试将 datetime.datetime.strptime 与我想要的格式一起使用,但它正在返回转换时间。

when = alldates[int(daypos[0])]
print when, type(when)

then = datetime.datetime.strptime(when, '%Y-%m-%d')
print then, type(then)

这是输出返回的内容:

2013-05-07 <type 'str'>
2013-05-07 00:00:00 <type 'datetime.datetime'>

我需要去掉时间:00:00:00.

最佳答案

print then.date()

你想要的是一个 datetime.date 对象。你所拥有的是一个 datetime.datetime 对象。您可以按上述方式在打印时更改对象,也可以在创建对象时执行以下操作:

then = datetime.datetime.strptime(when, '%Y-%m-%d').date()

关于python - 显示没有时间的 Python 日期时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26153795/

相关文章:

python - TypeError: must be string, not datetime.datetime 使用strptime时

python - 将 NaN 值插入 DataFrame 作为环

javascript - 我应该使用什么正则表达式来匹配这个日期模式 : DAY. month.YEAR?

mysql - 从 DATE 和 TIME 创建 DATETIME

python - Pandas 将日期时间字符串列转换为日期时间而不应用偏移

r - 收到错误 "number of items to replace is not a multiple of replacement length"

python - 如何使用 BeautifulSoup 从表中获取第一个和第三个 td?

python - 将工厂、 super 和子从一个模块中分离出来

python - TypeError : '<' not supported between instances of 'function' and 'str'

asp.net - 为什么 Time.strptime() 返回当前日期?