Home >Backend Development >Python Tutorial >How can you combine date and time columns into a single datetime column in Pandas?
Combining Date and Time Columns using Pandas
In pandas, combining date and time columns can be a necessary task for data analysis and manipulation. This can be achieved using various methods, one of which is through the pd.to_datetime() function.
Consider a DataFrame with separate 'Date' and 'Time' columns:
data = {'Date': ['01-06-2013', '02-06-2013', '02-06-2013', '02-06-2013', '02-06-2013', '03-06-2013', '03-06-2013', '03-06-2013', '03-06-2013', '04-06-2013'], 'Time': ['23:00:00', '01:00:00', '21:00:00', '22:00:00', '23:00:00', '01:00:00', '21:00:00', '22:00:00', '23:00:00', '01:00:00']} df = pd.DataFrame(data)
To combine these columns, you can simply concatenate them using the ' ' operator with a space as a separator:
df['DateTime'] = df['Date'] + ' ' + df['Time']
df['DateTime'] 0 01-06-2013 23:00:00 1 02-06-2013 01:00:00 2 02-06-2013 21:00:00 3 02-06-2013 22:00:00 4 02-06-2013 23:00:00 5 03-06-2013 01:00:00 6 03-06-2013 21:00:00 7 03-06-2013 22:00:00 8 03-06-2013 23:00:00 9 04-06-2013 01:00:00 Name: DateTime, dtype: object
Now, you can convert the combined 'DateTime' column to a datetime format using pd.to_datetime():
df['DateTime'] = pd.to_datetime(df['DateTime'])
df['DateTime'] 0 2013-01-06 23:00:00 1 2013-02-06 01:00:00 2 2013-02-06 21:00:00 3 2013-02-06 22:00:00 4 2013-02-06 23:00:00 5 2013-03-06 01:00:00 6 2013-03-06 21:00:00 7 2013-03-06 22:00:00 8 2013-03-06 23:00:00 9 2013-04-06 01:00:00 Name: DateTime, dtype: datetime64[ns]
Alternatively, you can specify the format of the 'DateTime' string using the format parameter:
df['DateTime'] = pd.to_datetime(df['DateTime'], format='%m-%d-%Y %H:%M:%S')
Remember to handle any conversion errors that may arise due to invalid date or time formats.
The above is the detailed content of How can you 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!