Home > Article > Backend Development > How to combine date and time columns into a single datetime column in Pandas?
Problem:
You have a Pandas dataframe with separate columns for date and time. You want to combine these columns to create a new column containing the combined datetime values.
Solution:
There are two common approaches to combine date and time columns in Pandas:
Using Concatenation with pd.to_datetime():
a. Concatenate the 'Date' and 'Time' columns with a space as a separator.
b. Convert the concatenated string to a datetime object using pd.to_datetime().
df['Combined_DateTime'] = pd.to_datetime(df['Date'] + ' ' + df['Time'])
Using pd.to_datetime() with a Format String:
a. Convert the 'Date' and 'Time' columns to datetime objects separately using pd.to_datetime().
b. Set the format parameter to specify the format of the datetime string.
df['Date'] = pd.to_datetime(df['Date'], format='%m-%d-%Y') df['Time'] = pd.to_datetime(df['Time'], format='%H:%M:%S') df['Combined_DateTime'] = pd.to_datetime(df['Date'] + ' ' + df['Time'])
Tips:
The above is the detailed content of How to combine date and time columns into a single datetime column in Pandas?. For more information, please follow other related articles on the PHP Chinese website!