從字串建立 Datetime
你常會拿到各式各樣格式的日期。許多資料來源都會把日期存成字串,例如網頁爬取、使用者輸入、或純文字檔等等。
對應 datetime 的格式字串可以在 strftime 查到。
假設你找到 1989 年 10 月的小型股災日期,存在字串 crash_text,以及 1990 年 7 月 3 日的衰退日期,存在字串 recession_text,而且兩者格式不同。你會如何在 Python 程式碼中表達這兩個日期?
本練習屬於課程
Intermediate Python for Finance
練習說明
- 建立一個格式字串,能對應到題目給的 1989 年小型股災的文字格式。
- 建立一個格式字串,能對應到 1990 年衰退的文字格式。
- 建立一個代表 1990 年衰退的 datetime。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
crash_text = "Friday the 13th, Oct, 1989"
# Create a format string mapping the text
crash_format_str = "%____ the %dth, %b, %____"
min_crash = datetime.datetime.strptime(crash_text, crash_format_str)
print(min_crash)
recession_text = "07/03/90"
# Create format string
recession_format_str = "%____/%____/%____"
# Create datetime from text using format string
nineties_rec = datetime.datetime.strptime(____, ____)
print(nineties_rec)