我想將不同的日期格式相互轉換。但是,當使用列印命令時,我仍然得到舊的資料格式。我在這里做錯了什么?
for row in df['created_at']:
row = datetime.strptime(row, "%Y-%m-%d %H:%M:%S").strftime('%d-%m-%Y')
print(df['created_at'])
uj5u.com熱心網友回復:
在您的代碼中,for 回圈遍歷每個元素,但不保存結果。如果你嘗試下面的代碼,你會發現你的代碼實際上運行良好,結果只是在操作后被“扔掉”了。
for row in df['created_at']:
row = datetime.strptime(row, "%Y-%m-%d %H:%M:%S").strftime('%d-%m-%Y')
print(row)
你想要做的是:
l = []
for row in df['created_at']:
l.append(datetime.strptime(row, "%Y-%m-%d %H:%M:%S").strftime('%d-%m-%Y'))
print(l)
一個更優雅的解決方案是使用串列理解:
df['created_at'] = [datetime.strptime(row, "%Y-%m-%d %H:%M:%S").strftime('%d-%m-%Y') for row in df['created_at']]
print(df['created_at'])
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/385646.html
上一篇:日期操作型別錯誤(日期時間包)
