關於 strptime 與 strftime 問題
2020/04/10 02:47 下午
Python網路爬蟲討論版
許義翔
觀看數:6
回答數:1
收藏數:0
pycrawler
pycrawler-d15
老師,您好
不好意思,在 Homework 中的這一段代碼
# 先到牌告匯率首頁,爬取所有貨幣的種類
url = "https://rate.bot.com.tw/xrt?Lang=zh-TW"
resp = requests.get(url)
resp.encoding = 'utf-8'
html = BeautifulSoup(resp.text, "lxml")
rate_table = html.find(name='table', attrs={'title':'牌告匯率'}).find(name='tbody').find_all(name='tr')
# 擷取匯率表格,把美金(也就是匯率表的第一個元素)擷取出來,查詢其歷史匯率
currency = rate_table[0].find(name='div', attrs={'class':'visible-phone print_hide'})
print(currency.get_text().replace(" ", "")) # 貨幣種類
# 針對美金,找到其「歷史匯率」的首頁
history_link = rate_table[0].find(name='td', attrs={'data-table':'歷史匯率'})
history_rate_link = "https://rate.bot.com.tw" + history_link.a["href"] # 該貨幣的歷史資料首頁
#
# 到貨幣歷史匯率網頁,選則該貨幣的「歷史區間」,送出查詢後,觀察其網址變化情形,再試著抓取其歷史匯率資料
#
# 用「quote/年-月」去取代網址內容,就可以連到該貨幣的歷史資料
# 修正 history 之後的連結字串,更換特定時間
quote_history_url = history_rate_link.replace("history", "quote/2020-04")
resp = requests.get(quote_history_url)
resp.encoding = 'utf-8'
history = BeautifulSoup(resp.text, "lxml")
history_table = history.find(name='table', attrs={'title':'歷史本行營業時間牌告匯率'}).find(name='tbody').find_all(name='tr')
#
# 擷取到歷史匯率資料後,把資料彙整起來並畫出趨勢圖
#
date_history = list()
history_buy = list()
history_sell = list()
for history_rate in history_table:
# 擷取日期資料
date_string = history_rate.a.get_text()
print(date_string)
# 這裏將日期字元串轉成日期對象(datetime object),再轉換成 String
date = datetime.strptime(date_string, '%Y/%M/%d')#.strftime('%Y/%M/%d') # 轉換日期格式
print(date)
date_history.append(date) # 日期歷史資料
history_ex_rate = history_rate.find_all(name='td', attrs={'class':'rate-content-cash text-right print_table-cell'})
history_buy.append(float(history_ex_rate[0].get_text())) # 歷史買入匯率
history_sell.append(float(history_ex_rate[1].get_text())) # 歷史賣出匯率
# 將匯率資料建成dataframe形式
HistoryExchangeRate = pd.DataFrame({'date': date_history,
'buy_rate':history_buy,
'sell_rate':history_sell})
HistoryExchangeRate = HistoryExchangeRate.set_index('date') # 指定日期欄位為datafram的index
HistoryExchangeRate = HistoryExchangeRate.sort_index(ascending=True)
# 畫出歷史匯率軌跡圖
plt.figure(figsize=(10, 8))
HistoryExchangeRate[['buy_rate','sell_rate']].plot() # x=['date'], y=[['buy_rate','sell_rate']]
plt.legend(loc="upper left")
plt.show()
關於 print(date_string) 所輸出的內容如下
2020/04/10
2020/04/09
2020/04/08
2020/04/07
2020/04/06
2020/04/01
而 date = datetime.strptime(date_string, '%Y/%M/%d') 所屬出的卻是內容如下
2020-01-10 00:04:00
2020-01-09 00:04:00
2020-01-08 00:04:00
2020-01-07 00:04:00
2020-01-06 00:04:00
2020-01-01 00:04:00
再經由 strftime('%Y/%M/%d') 轉換,所屬出的內容如下
2020/04/10
2020/04/09
2020/04/08
2020/04/07
2020/04/06
2020/04/01
Question
為什麼經由 strptime() 解析出來的格式,時間會有不一致的狀況?都變成 1月份?
在經由 strftime() 又會轉換回來?
我已知
strptime 將 datetime string 轉換成 object
p表示parse,表示分析的意思,所以strptime是給定一個時間字元串和分析模式,返回一個時間對象(紀錄成時間元組)
strftime 將 datetime object 轉換成 String
f表示format,表示格式化,和strptime正好相反,要求給一個時間對象和輸出格式,返回一個時間字元串
strftime 可以用來獲得當前時間,但是需要注意的是獲得的時間是服務器的時間,但這個解析出來的時間我無法與 strptime 做連結,可否再請您進一步說明嗎?謝謝!