目前我正在嘗試使用以下代碼將當前日期修剪爲日,月和年。在Python中修改日期的有效方法是什麼?
#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的專業,因爲我掌握這門語言了幾個月前的,但我想在這裏瞭解幾件事情:
- 爲什麼我收到這2017-07如果str .rpartition()應該在聲明某種排序分隔符( - ,/,「」)後分隔一個字符串?我期待收到2017 ...
- 有沒有一種有效的方法來分隔日,月和年?我不想用我的不安全代碼重複同樣的錯誤。
我在下面的技術中試過我的代碼。設置: 本地計算機與Python 3.5.2(64位),Python的3.6.1(64位)和repl.it與Python 3.6.1
Try the code online, copy and paste the line codes
可能重複[如何獲取當前時間在python和分解成年,月,日,小時,分鐘?](https://stackoverflow.com/questions/30071886/how-to-獲得電流 - 時間 - 在 - python的通斷,上成 - 年月日小時) – Dijkgraaf
可能的但不能解釋問題1. –
閱讀分隔https://python-reference.readthedocs.io/en/latest/docs/str/rpartition.html&分區https ://python-reference.readthedocs.io/en/latest/docs/str/partition.html你想要一年的分區。不是rpartition – Dijkgraaf