Home > Software design >  How to create a datetime column in pandas based on two columns date and time?
How to create a datetime column in pandas based on two columns date and time?

Time:02-24

Lets say I have following DataFrame:

import pandas as pd
df = pd.DataFrame({"Date":["2022-01-01", "2022-01-02", "2022-01-03"], "Time":[0,1,10]})

I want another column which is a datetime using the Date and the Time Columns.

Expected result

         Date  Time            DateTime
0  2022-01-01     0 2022-01-01 00:00:00
1  2022-01-02     1 2022-01-02 01:00:00
2  2022-01-03    10 2022-01-03 10:00:00

Trial

I tried this failed solution:

df["DateTime"] = str(df["Date"])   " "   str(df["Time"])   ":00"

Which outputs:

>>> df
         Date  Time                                           DateTime
0  2022-01-01     0  0    2022-01-01\n1    2022-01-02\n2    2022-01...
1  2022-01-02     1  0    2022-01-01\n1    2022-01-02\n2    2022-01...
2  2022-01-03    10  0    2022-01-01\n1    2022-01-02\n2    2022-01...

CodePudding user response:

You can just do Date and Time add with to_datetime and to_timedelta

df['new'] = pd.to_datetime(df['Date'])   pd.to_timedelta(df['Time'],unit='hour')
df
Out[388]: 
         Date  Time                 new
0  2022-01-01     0 2022-01-01 00:00:00
1  2022-01-02     1 2022-01-02 01:00:00
2  2022-01-03    10 2022-01-03 10:00:00

CodePudding user response:

One solution would be the following:

df["DateTime"] = df["Date"].astype(str)   " "   df["Time"].astype(str)   ":00"

Then convert to datetime:

df["DateTime"] = pd.to_datetime(df["DateTime"])

Hence the output is as expected:

>>> df
         Date  Time            DateTime
0  2022-01-01     0 2022-01-01 00:00:00
1  2022-01-02     1 2022-01-02 01:00:00
2  2022-01-03    10 2022-01-03 10:00:00
  • Related