How do I combine two date and time columns into one in a Pandas dataframe?

To combine two date and time columns into one in a Pandas dataframe, you can use the pandas.to_datetime() function to convert your columns to datetime objects, and then use the pandas.DataFrame.combine() function to combine the two columns into one.


You can use the following syntax to combine date and time columns in a pandas DataFrame into a single column:

df['datetime'] = pd.to_datetime(df['date'] + ' ' + df['time'])

Note that this syntax assumes the date and time columns are both currently strings.

If both columns aren’t already strings, you can use astype(str) to convert them to strings:

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

The following example shows how to use this syntax in practice.

Example: Combine Date and Time Columns in Pandas

Suppose we have the following pandas DataFrame that contains a date column and a time column:

import pandas as pd

#create DataFrame
df = pd.DataFrame({'date': ['10-1-2023', '10-4-2023', '10-6-2023', '10-6-2023',
                            '10-14-2023', '10-15-2023', '10-29-2023'],
                   'time': ['4:15:00', '7:16:04', '9:25:00', '10:13:45',
                            '15:30:00', '18:15:00', '23:15:00']})

#view DataFrame
print(df)

         date      time
0   10-1-2023   4:15:00
1   10-4-2023   7:16:04
2   10-6-2023   9:25:00
3   10-6-2023  10:13:45
4  10-14-2023  15:30:00
5  10-15-2023  18:15:00
6  10-29-2023  23:15:00

Suppose we would like to create a new column called datetime that combines the values in the date and time columns.

We can use the following syntax to do so:

#create new datetime column
df['datetime'] = pd.to_datetime(df['date'] + ' ' + df['time'])

#view updated DataFrame
print(df)

         date      time            datetime
0   10-1-2023   4:15:00 2023-10-01 04:15:00
1   10-4-2023   7:16:04 2023-10-04 07:16:04
2   10-6-2023   9:25:00 2023-10-06 09:25:00
3   10-6-2023  10:13:45 2023-10-06 10:13:45
4  10-14-2023  15:30:00 2023-10-14 15:30:00

Notice that the new datetime column has successfully combined the values from the date and time columns into one column.

We can also use the dtypes function to check the data types of each column in the DataFrame:

#view data type of each column
df.dtypes

date                object
time                object
datetime    datetime64[ns]
dtype: object

From the output we can see that the date and time columns are both objects (i.e. strings) and the new datetime column is a datetime.

Note: You can find the complete documentation for the pandas to_datetime() function .

x