現在、次のコードを使用して、現在の日付を日、月、年にトリムしようとしています。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の専門家ではないが、私はここにいくつかのことを理解したい:
- は、なぜ私はstrの場合は、この2017から07を受け取りました.rpartition()はあなたが何らかのソートセパレータ( - 、/、 "")を宣言したら、文字列を区切っていますか?私は2017年を受け取ることを期待していた...
- 日、月、年を分ける効率的な方法はありますか?私は安全でないコードで同じミスを繰り返すことは望まない。
私は以下の技術で自分のコードを試しました。セットアップ:Pythonの3.6.1でのPython 3.5.2(x64)の、Pythonの3.6.1(x64)のとrepl.itと ローカルマシン
Try the code online, copy and paste the line codes
の可能性のある重複(https://stackoverflow.com/questions/30071886/how-to- [pythonで現在の時刻を取得し、年、月、日、時、分に分割する方法は?] get-current-time-in-python-and-break-up-into月 - 日 - 時 - 分) – Dijkgraaf
可能ですが、質問1については説明しません。 –
rpartitionの読み取りhttps://python-reference.readthedocs.io/en/latest/docs/str/rpartition.html&パーティションhttps ://python-reference.readthedocs.io/en/latest/docs/str/partition.html今年のパーティションが必要です。 – Dijkgraaf