如何在Pandas DataFrame中合并日期时间列并转换为datetime对象
问题描述
需要将DataFrame中的date列和time列合并为datetime对象,该DataFrame从剪贴板导入,所有字段初始为字符串格式,运行代码后出现报错。
初始数据
new_data Out[90]: date time price price2 price3 price4 var volume 0 29/09/21 05:07:07 1 1 1 1 1 1 1 01/10/21 06:03:07 1 1 1 1 1 1
执行的代码
- 拼接date和time列
new_data.time=(new_data.date+';'+new_data.time)
拼接后的数据:
new_data Out[92]: date time price price2 price3 price4 var volume 0 29/09/21 29/09/21;05:07:07 1 1 1 1 1 1 1 01/10/21 01/10/21;06:03:07 1 1 1 1 1 1
- 转换为datetime对象
pandas.to_datetime(new_data.time, format='%d/%m/%Y;%H:%M:%S')
报错信息
Traceback (most recent call last): File "C:\Users\PC1\anaconda3\envs\tf\lib\site-packages\pandas\core\tools\datetimes.py", line 456, in _convert_listlike_datetimes values, tz = conversion.datetime_to_datetime64(arg) File "pandas\_libs\tslibs\conversion.pyx", line 350, in pandas._libs.tslibs.conversion.datetime_to_datetime64 TypeError: Unrecognized value type: <class 'str'> During handling of the above exception, another exception occurred: Traceback (most recent call last): File "<ipython-input-93-74451701a415>", line 1, in <module> pandas.to_datetime(new_data.time, format='%d/%m/%Y;%H:%M:%S') File "C:\Users\PC1\anaconda3\envs\tf\lib\site-packages\pandas\core\tools\datetimes.py", line 805, in to_datetime values = convert_listlike(arg._values, format) File "C:\Users\PC1\anaconda3\envs\tf\lib\site-packages\pandas\core\tools\datetimes.py", line 460, in _convert_listlike_datetimes raise e File "C:\Users\PC1\anaconda3\envs\tf\lib\site-packages\pandas\core\tools\datetimes.py", line 424, in _convert_listlike_datetimes arg, format, exact=exact, errors=errors File "pandas\_libs\tslibs\strptime.pyx", line 144, in pandas._libs.tslibs.strptime.array_strptime ValueError: time data '29/09/21;05:07:07' does not match format '%d/%m/%Y;%H:%M:%S' (match)
原因说明
报错的核心原因是日期格式符不匹配:%Y对应的是4位完整年份(例如2021),但你数据中的年份只有2位(例如21),所以无法解析。
解决方案
将格式字符串中的大写%Y替换为小写%y即可,%y专门用于匹配2位长度的年份,修正后的代码如下:
pandas.to_datetime(new_data.time, format='%d/%m/%y;%H:%M:%S')
内容的提问来源于stack exchange,提问作者realbro
相关产品推荐
相关产品推荐

