Skip to main content
 首页 » 编程设计

python之从字符串 Pandas 数据框中提取日期

2024年10月24日29shangdawei

我在 pandas 数据框中有这个 Date_X 列,它是一个对象。我无法在这里使用 pandas to_datetime 函数。我想将此列转换为 1 到 365 的范围,我可以使用它进行分析。

29JAN14:21:16:00 
01FEB14:00:11:00 
30JAN14:15:11:00 
01FEB14:00:07:00 
29JAN14:19:31:00 
30JAN14:23:52:00 
29JAN14:19:18:00 
30JAN14:16:46:00 
30JAN14:21:39:00 
31JAN14:17:40:00 
01FEB14:00:16:00 

请您参考如下方法:

您可以使用 pandas.to_datetime()通过使用 format 关键字参数显式提供格式。示例 -

import pandas as pd 
pd.to_datetime(dataframe['column'],format='%d%b%y:%H:%M:%S') 

格式说明-

%d - 2 digit date
%b - 2 letter month abbreviation
%y - 2 digit year
%H - 2 digit hour (24-hour format)
%M - Minutes
%S - Seconds

演示 -

In [46]: pd.to_datetime('29JAN14:21:16:00') #Not working 
Out[46]: '29JAN14:21:16:00' 
 
In [48]: pd.to_datetime('29JAN14:21:16:00',format='%d%b%y:%H:%M:%S') #Working 
Out[48]: Timestamp('2014-01-29 21:16:00')