Python Pandas - 将字符串数据转换为日期时间类型
要将字符串数据转换为实际日期,即日期时间类型,请使用to_datetime()方法。首先,让我们创建一个包含3个类别的DataFrame,其中一个是日期字符串-
dataFrame = pd.DataFrame({ 'Product Category': ['Computer', 'Mobile Phone', 'Electronics', 'Stationery'],'Product Name': ['Keyboard', 'Charger', 'SmartTV', 'Chairs'],'Date_of_Purchase': ['10/07/2021','20/04/2021','25/06/2021','15/02/2021'], })
使用to_datetime()-将日期字符串转换为实际日期-
dataFrame['Date_of_Purchase'] = pd.to_datetime(dataFrame['Date_of_Purchase'])
示例
以下是完整的代码-
import pandas as pd #createadataframe dataFrame = pd.DataFrame({ 'Product Category': ['Computer', 'Mobile Phone', 'Electronics', 'Stationery'],'Product Name': ['Keyboard', 'Charger', 'SmartTV', 'Chairs'],'Date_of_Purchase': ['10/07/2021','20/04/2021','25/06/2021','15/02/2021'], }) print"\nDataFrame...\n",dataFrame #convertdatestringstoactualdates dataFrame['Date_of_Purchase'] = pd.to_datetime(dataFrame['Date_of_Purchase']) print"\nUpdated DataFrame (string dates converted to dates)...\n",dataFrame输出结果
这将产生以下输出-
DataFrame... Date_of_Purchase Product Category Product Name 0 10/07/2021 Computer Keyboard 1 20/04/2021 Mobile Phone Charger 2 25/06/2021 Electronics SmartTV 3 15/02/2021 Stationery Chairs Updated DataFrame (string dates converted to dates)... Date_of_Purchase Product Category Product Name 0 2021-10-07 Computer Keyboard 1 2021-04-20 Mobile Phone Charger 2 2021-06-25 Electronics SmartTV 3 2021-02-15 Stationery Chairs