转换熊猫中的自定义日期格式

时间:2019-01-28 05:57:24

标签: python pandas datetime parsing dataframe

在数据框中,我想将多种日期格式更改为通用格式。

1)var output = String.Join('.', input.Split(',')); //--> 30.32.13

2)"12/01/2011 11:25 PM"

3)"Thu, Dec 1 8:15 AM"

4)"Dec.01, 2011 4:00 p.m"

5)"2011 - 12 - 01 10:33 AM"

6)"12/1/2011 12:18PM "

7)"12/1/11 2:06 PM (-05:00)"

8)"2:07 PMDec 01"

"12:18 PM, Dec 01"在以下格式中失败:

6)parse(x)

7)"12/1/11 2:06 PM (-05:00)"

是否可以为这些自定义日期格式创建参数?

1 个答案:

答案 0 :(得分:0)

使用:

import pandas as pd
pd.to_datetime(DateString, format=FormatString)

下面是示例代码:

date_old = '12/01/2011 11:25 PM'
date_new = pd.to_datetime(date_old, format='%d/%m/%Y %I:%M %p')

date_old = 'Dec.01, 2011 4:00 p.m'
date_new = pd.to_datetime(date_old[:-2] + 'm', format='%b.%d, %Y %I:%M %p')

date_old = '2011 - 12 - 01 10:33 AM'
date_new = pd.to_datetime(date_old, format='%Y - %m - %d %I:%M %p')

date_old = '12/1/2011 12:18PM '
date_new = pd.to_datetime(date_old, format='%d/%m/%Y %I:%M%p ')

from datetime import timedelta
date_old = '12/1/11 2:06 PM (-05:00)'
date_new = pd.to_datetime(date_old[:-9], format='%d/%m/%y %I:%M %p') - timedelta(hours=int(date_old[-6:-4]), minutes=int(date_old[-3:-1]))

date_old = '2:07 PMDec 01'
date_new = pd.to_datetime(date_old, format='%I:%M %p%b %d')

date_old = "12:18 PM, Dec 01"
date_new = pd.to_datetime(date_old, format='%I:%M %p, %b %d')

有关合法格式代码,请参阅https://www.w3schools.com/python/python_datetime.asp