【发布时间】:2017-12-25 11:46:36
【问题描述】:
目前我正在尝试使用以下代码将当前日期修剪为日、月和年。
#Code from my local machine
from datetime import datetime
from datetime import timedelta
five_days_ago = datetime.now()-timedelta(days=5)
# result: 2017-07-14 19:52:15.847476
get_date = str(five_days_ago).rpartition(' ')[0]
#result: 2017-07-14
#Extract the day
day = get_date.rpartition('-')[2]
# result: 14
#Extract the year
year = get_date.rpartition('-')[0])
# result: 2017-07
我不是 Python 专业人士,因为几个月前我就掌握了这门语言,但我想在这里了解一些事情:
- 如果 str.rpartition() 应该在您声明某种排序分隔符(-、/、“”)后分隔字符串,为什么我会收到此 2017-07?我期待收到 2017 年...
- 有没有一种有效的方法来分隔日、月和年?我不想对我的不安全代码重复同样的错误。
我在以下技术中尝试了我的代码。设置: 使用 Python 3.5.2 (x64)、Python 3.6.1 (x64) 的本地机器和使用 Python 3.6.1 的 repl.it
【问题讨论】:
-
可能,但这并不能解释问题 1。
-
读取 rpartition python-reference.readthedocs.io/en/latest/docs/str/… & partition python-reference.readthedocs.io/en/latest/docs/str/… 你想要一年的分区。不分区
标签: python python-3.x