Convert custom date formats in pandas

2019-08-27 23:14发布

In my dataframe, I have multiple date formats that I want to change into a universal format.

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

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

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

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

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

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

7) "2:07 PMDec 01"

8) "12:18 PM, Dec 01"

parse(x) fails in these formats:

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

7) "2:07 PMDec 01"

Is there any way to create arguments for these custom date formats?

1条回答
虎瘦雄心在
2楼-- · 2019-08-27 23:54

Use:

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

Following the code for your examples:

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')

Please refer to https://www.w3schools.com/python/python_datetime.asp for a legal format codes.

查看更多
登录 后发表回答