Home  >  Article  >  Backend Development  >  How to combine date and time columns into a single datetime column in Pandas?

How to combine date and time columns into a single datetime column in Pandas?

Barbara Streisand
Barbara StreisandOriginal
2024-11-16 22:33:03765browse

How to combine date and time columns into a single datetime column in Pandas?

Combining Date and Time Columns 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:

  1. 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'])
  2. 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:

  • You can use %%timeit to benchmark the performance of the different approaches.
  • If the 'Date' and 'Time' columns contain NaNs or invalid values, consider using the errors parameter in pd.to_datetime() to handle such cases.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn