首页 > 解决方案 > 在 Python 中打印年/月/日?`

问题描述

如何以以下格式打印当前日期?

年/月/日

我一直在使用下面的,但它增加了一个额外的空间。我需要它看起来像“2020/9/14”而不是“2020 / 9 / 14”。有什么想法吗?下面是后一个选项的当前代码。

str(todays_date.year)
str(todays_date.month)
str(todays_date.day)
dash = "/"
str(dash)

print(todays_date.year,dash,todays_date.month,dash,todays_date.day)

标签: python

解决方案


像这样:

from datetime import datetime

print(datetime.today().strftime('%Y/%-m/%-d'))

更新:我在其中添加了连字符,意识到您不希望在一位数的月份或日期上使用前导零。

今天的结果:

2020/9/14

如果您想使用日期中的各个值并进行自己的格式化,您可以这样做以获得相同的结果:

print("{}{}{}{}{}".format(todays_date.year,dash,todays_date.month,dash,todays_date.day))

推荐阅读