python - 在 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)
解决方案
像这样:
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))
推荐阅读
- c# - 在 Azure 中的 Active Directory 上验证用户身份
- struct - 使用了 unnest(),但仍然无法访问类型为 ARRAY 的值上的字段文本
>、大查询 - loopbackjs - 是否有任何环回 3 功能可以帮助修改然后构建过滤器?
- python - 如何在 django 中显示动态下拉菜单?
- java - 为什么在ios系统中不能处理Android应用程序?
- php - 多数据库开发模式
- spring - spring post加载资源失败:服务器响应状态为400(错误请求)
- tfs - 如何找到我现在拥有的文件版本?
- php - 如何修复错误 Kohana_Exception [0]:Model_Emails 类中不存在类型属性
- java - 如何在 Java 中加入两个位集?