Ernsthaft
Ernsthaft

Reputation: 177

Convert date and time columns in a pandas df to a timestamp

i am new to python and used to code in R. I have a Pandas df that has a column of dates and times.

                     date   time 
     0           2018-06-25  07:32:25    
     1           2018-06-25  09:36:38    
     2           2018-06-25  13:31:47   
     3           2018-06-25  13:29:56   
     4           2018-06-29  04:00:13

I used to select these columns and create numercial vectors to convert them into one vector of timestamps in R. Is there a possibility to do something similar in python? I already tried this:

strtime = df1['time'].astype(str)
strdate = df1['date'].astype(str)

timestamp = pd.to_datetime(strdate + ' ' + strtime)

But it gives me the output:

"ValueError: Unknown string format"

I believe this might be an easy task so please be kind.

Upvotes: 1

Views: 51

Answers (1)

jezrael
jezrael

Reputation: 862406

I think there is problem some bad values, solution is parameter errors='coerce' for convert them to NaT:

timestamp = pd.to_datetime(strdate + ' ' + strtime, errors='coerce')

You can check these values by:

print (df1[pd.to_datetime(strdate + ' ' + strtime, errors='coerce').isnull()])

Upvotes: 2

Related Questions