df 在 Pandas 中有如下数据
"val1" 6972.75 01-AUG-18 08.11.51.319 AM
"val2" 6974.25 01-OCT-18 08.12.22.322 AM
我正在使用代码
pd.to_datetime(df['TIME'], format="%d-%m-%Y %H.%M.%S.%f")
当我运行代码时,它在下面给出错误
ValueError: time data '01-AUG-18 08.11.51.319 AM' does not match format '%d-%b-%Y %H.%M.%S.%f' (match)
答案 0 :(得分:2)
最后还有额外的 AM
。尝试将其剥离:
pd.to_datetime(df['TIME'].str[:-3], format="%d-%m-%Y %H.%M.%S.%f")
或者更安全是为它们包含格式指令:
# notice the extra %p
pd.to_datetime(df['TIME'], format="%d-%m-%Y %H.%M.%S.%f %p")
或者让pandas猜测,这更简单但运行时间更长:
pd.to_datetime(df['TIME'], dayfirst=True)
答案 1 :(得分:2)
你的格式全乱了。您使用了错误的月份和年份格式,您可以使用 %p
处理 AM/PM。 (大多数格式都可以在 datetime
docs
%b #Month as locale’s abbreviated name: [Jan, Feb, …, Dec (en_US)]
%y #Year without century as a zero-padded decimal number: [00, 01, …, 99]
%p #Locale’s equivalent of either AM or PM: [AM, PM (en_US)]
import pandas as pd
df = pd.DataFrame({'TIME': ['01-AUG-18 08.11.51.319 AM',
'01-OCT-18 08.12.22.322 AM']})
pd.to_datetime(df['TIME'], format="%d-%b-%y %H.%M.%S.%f %p", errors='coerce')
#0 2018-08-01 08:11:51.319
#1 2018-10-01 08:12:22.322
#Name: TIME, dtype: datetime64[ns]