開始使用免費開始

轉換日期格式-明確方法

來看看前一個練習中的其中一個日期。

  • Sale A: 4000 on 14/02/2018

我們用 datetime 函式庫辨識日 d、月 m 和年 y,這有助於從不同日期格式的資料集中擷取資料。不過,如果情境是要把日期格式轉換成指定格式該怎麼做?

在這個練習中,你要把 Sale A 從 14/02/2018 轉成與 Sale B 相同的日期格式(也就是 14 February 2018)。

我們可以用 Python 內建函式輕鬆完成。記得,要分割字串可以使用 .split() 方法。

本練習的輸入是 Sale A 的日期時間。

本練習屬於課程

使用 Python 進行財務預測

檢視課程

練習說明

  • 建立變數 dt,其中包含你想轉換為新格式的日期之字串(也就是 Sale A)。
  • 建立月份字典 mm,用來指定每個數字對應的月份名稱,格式為 {'number':'month name'}
  • 以字元 / 分割 dt 字串,並將值指派給變數 daymonthyear
  • 透過串接字串並使用月份字典,將指定月份轉成新格式並列印結果。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

# Set the variable for the datetime to convert
dt = '____'

# Create the dictionary for the month values
mm = {'01': '____', '____': 'February', '____': '____'}

# Split the dt string into the different parts
____, ____, year = dt.split('____')

# Print the concatenated date string
print(____ + ' ' + ____[____] + ' ' + ____)
編輯並執行程式碼