0

I have a DataFrame with the following format:

date        time
12/8/2022   5:15 AM
12/9/2022   8:55 PM
12/10/2022. 9:20 AM

I would like to create a new df column with this data in timestamp format with millitary time (24h time format):

2022-12-08 05:15:00
2022-12-09 20:55:00
2022-12-10 09:20:00

I would like to then remove/replace the two columns with the individual date and time and have a column with the timestamp.

I have tried using methods like pd.to_datetime but still having dificulties getting the formatting right.

pythonic
  • 33
  • 4

2 Answers2

1

You can use:

df['new_date']=pd.to_datetime(df['date'].astype(str) +' ' + df['time'].astype(str))

'''
    date         time     new_date
0   12/8/2022   5:15 AM   2022-12-08 05:15:00
1   12/9/2022   8:55 PM   2022-12-09 20:55:00
2   12/10/2022  9:20 AM   2022-12-10 09:20:00


'''
Bushmaster
  • 4,196
  • 3
  • 8
  • 28
0

%I is for the 12-hour

%H to return the 24-hour format.

df['time'] = pd.to_datetime(df['time']).dt.strftime('%H:%M:%S')
df['date'] = df['date'] + df['time']
print(df)

Gives #

                 date      time
0   12/8/202205:15:00  05:15:00
1   12/9/202220:55:00  20:55:00
2  12/10/202209:20:00  09:20:00
>>>