简体   繁体   中英

Convert pandas dataframe date and time string into datetime

I have a table like

| name | time1                   | time2                   |
| ---- | ----------------------- | ----------------------- |
| one  | 10/18/2011 07:38:19 PM  | 10/18/2008 07:40:30 PM  |
| two  | 09/15/2006 08:40:21 AM  | 09/15/2002 08:45:26 AM  |

I am trying to convert columns time1 and time2 from string into datetime using the pandas to_datetime , from researching around it should be:

new_df = pd.to_datetime(df['time1'], format='MM/dd/yyyy %I:%M:%S %p')

However I keep getting this error no matter how I try using the to_datetime:

ValueError: Cannot convert column into bool

Can anyone point me the right way?

Here is one way to convert the string (note change to the format argument of pd.to_datetime ):

import pandas as pd

df = pd.DataFrame(
    {'name': ['one', 'two'],
    'time1': ['10/18/2011 07:38:19 PM', '09/15/2006 08:40:21 AM'],
    'time2': ['10/18/2008 07:40:30 PM', '09/15/2002 08:45:26 AM']
})
pd.to_datetime(df['time1'], format='%m/%d/%Y %I:%M:%S %p')

0   2011-10-18 19:38:19
1   2006-09-15 08:40:21
Name: time1, dtype: datetime64[ns]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM