在 Python 中以 YYYY-MM-DD 格式获取今天的日期? [英] Getting today's date in YYYY-MM-DD in Python?
本文介绍了在 Python 中以 YYYY-MM-DD 格式获取今天的日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用:
str(datetime.datetime.today()).split()[0]
以 YYYY-MM-DD
格式返回今天的日期.
有没有更简单的方法来实现这一目标?
解决方案
您可以使用 strftime:
<预><代码>>>>从日期时间导入日期时间>>>datetime.today().strftime('%Y-%m-%d')'2021-01-26'此外,对于任何也在最后寻找零填充的小时、分钟和秒的人:(评论来自 Gabriel订书钉)
<预><代码>>>>datetime.today().strftime('%Y-%m-%d-%H:%M:%S')'2021-01-26-16:50:03'I'm using:
str(datetime.datetime.today()).split()[0]
to return today's date in the YYYY-MM-DD
format.
Is there a less crude way to achieve this?
解决方案
You can use strftime:
>>> from datetime import datetime
>>> datetime.today().strftime('%Y-%m-%d')
'2021-01-26'
Additionally, for anyone also looking for a zero-padded Hour, Minute, and Second at the end: (Comment by Gabriel Staples)
>>> datetime.today().strftime('%Y-%m-%d-%H:%M:%S')
'2021-01-26-16:50:03'
这篇关于在 Python 中以 YYYY-MM-DD 格式获取今天的日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文