轉換日期格式:基礎
歐洲的銷售區域 A 與澳洲的銷售區域 B 使用不同的日期格式。
- 銷售 A: 4000,日期為 14/02/2018
- 銷售 B: 3000,日期為 2 March 2018
如果要彙總或比較銷售期間,就需要把日期轉為相同的格式。我們可以使用 datetime 函式庫與 datetime.strptime(date_string, format) 方法,並搭配以下指令輕鬆完成:
| Directive | Meaning | Example |
|---|---|---|
| %d | Day of the month as a zero-padded decimal number | 01, 02, …, 31 |
| %b | Month as locale's abbreviated name | Jan, Feb, …, Dec |
| %B | Month as locale's full name | January, …, December |
| %m | Month as a zero-padded decimal number | 01, 02, …, 12 |
| %y | Year without century as a zero-padded decimal number | 00, 01, …, 99 |
| %Y | Year with century as a decimal number | 1970, 1988, 2001, 2013 |
本練習屬於課程
使用 Python 進行財務預測
練習說明
- 匯入
datetime函式庫。 - 建立一個
dt_object,把每筆銷售的日期轉換為標準的 日-月-年 格式。 - 印出每個結果以便比較。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Import the datetime python library
from ____ import ____
# Create a dt_object to convert the first date and print the month result
dt_object1 = datetime.strptime('14/02/2018', '____')
print(____)
# Create a dt_object to convert the second date and print the month result
dt_object2 = datetime.strptime('2 March 2018', '____')
print(____)