在Pandas中将自定义对象转换为标准日期时间对象

时间:2018-12-19 10:10:39

标签: python pandas

我有一个充满日期,时间的奇数系列,我想将其转换为DateTime以便进行一些操作

allSubs['Subscribed']
0        12th December, 08:08
1        11th December, 14:57
2        10th December, 21:40
3         7th December, 21:39
4         5th December, 14:51
5        30th November, 15:36

当我在其上调用pd.to_datetime(allSubs['Subscribed'])时,出现错误'超出范围的纳秒级时间戳:1-12-12 08:08:00'。我尝试使用参数errors='coerce',但这只会返回一系列nat。我想将系列转换为格式为YYYY-MM-DD的pandas datetime对象。

我已经研究过使用datetime.strptime,但找不到有效的方法来对系列进行此操作。

任何帮助,不胜感激!

1 个答案:

答案 0 :(得分:2)

使用:

from dateutil import parser

allSubs['Subscribed'] = allSubs['Subscribed'].apply(parser.parse)
print (allSubs)

           Subscribed
0 2018-12-12 08:08:00
1 2018-12-11 14:57:00
2 2018-12-10 21:40:00
3 2018-12-07 21:39:00
4 2018-12-05 14:51:00
5 2018-11-30 15:36:00

或者使用正则表达式使用replace,也必须指定年份,然后通过自定义format-to_datetime使用http://strftime.org/

s = allSubs['Subscribed'].str.replace(r'(\d)(st|nd|rd|th)', r'\1 2018')
allSubs['Subscribed'] = pd.to_datetime(s, format='%d %Y %B, %H:%M')
print (allSubs)
           Subscribed
0 2018-12-12 08:08:00
1 2018-12-11 14:57:00
2 2018-12-10 21:40:00
3 2018-12-07 21:39:00
4 2018-12-05 14:51:00
5 2018-11-30 15:36:00