Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
384 views
in Technique[技术] by (71.8m points)

Convert object to datetime stamp in python pandas. Where day has no leading zero

I cant seem to convert this dataframe column to a datetime stamp.

Date_Last_Modified
January 1 2021 7:36:32 pm
January 11 2021 7:36:32 pm... ect

The dtype is an object and the %e does not work nor does the %-d work. this is my command.

df['Date_Last_Modified'] = pd.to_datetime(df['Date_Last_Modified'], format='%B %d %Y %I:%M:%S %p')

Here is the error

ValueError: time data 'Date Last Modified' does not match format '%B %d %Y %I:%M:%S %p' (match)

or

df['Date_Last_Modified'] = pd.to_datetime(df['Date_Last_Modified'], format='%B %e %Y %I:%M:%S %p')

ValueError: 'e' is a bad directive in format '%B %e %Y %I:%M:%S %p'


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If want test what values are wrong add errors='coerce' and test missing values:

print (df[pd.to_datetime(df['Date_Last_Modified'], 
                         format='%B %d %Y %I:%M:%S %p', 
                         errors='coerce').isna()])

Here is simplier solution - first converted bad values to NaNs by parameter errors='coerce' and then using DataFrame.dropna remove this rows:

df['Date_Last_Modified'] =  pd.to_datetime(df['Date_Last_Modified'], 
                                           format='%B %d %Y %I:%M:%S %p', 
                                           errors='coerce')

df = df.dropna(subset=['Date_Last_Modified'])

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...