在我的数据帧,我有我想更换成统一格式多种日期格式。
1) "12/01/2011 11:25 PM"
2) "Thu, Dec 1 8:15 AM"
3) "Dec.01, 2011 4:00 pm"
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)
在这些格式失败:
6) "12/1/11 2:06 PM (-05:00)"
7) "2:07 PMDec 01"
有没有什么方法来创建这些自定义的日期格式参数呢?
采用:
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的法律格式代码。