Pandas combine date and time

Posted on

This short article explains how you can create a Pandas timestamp object by combining date and time strings.

Pandas Combine() Function

Pandas provides us with the timestamp.combine() function which allows us to take date and time string values ​​and combine them into a single Pandas timestamp object.

The function syntax is as shown below:

1

Timestamp.combine(Date, time)

The function accepts two main parameters:

  1. Date – refers to the datetime.date object indicating the date string.
  2. Time – specifies the datetime.time object.

The function returns the objected timestamp from the passed date and time parameters.

Example

An example is shown in the example below:

1
2
3
4
5
6

# import pandas
import panda as pd
# import date and time
of date hour import Date, time
you = pd.Timestamp.combine(Date(2022,4,11), time(13,13,13))
to print(you)

We use the date and time functions of the datetime module to create datetime objects in this example.

We then combine the objects into a Pandas timestamp using the combine function. The code above should return:

Combine date and time columns

Suppose you have a Pandas DataFrame with date and time columns? Consider the example DataFrame below:

1
2
3
4
5

# import pandas
# from import date datetime, hour
Data = {‘Appointment’: [date(2022,4,11), date(2023,4,11)], ‘time’: [time(13,13,13), time(14,14,14)]}
df = pd.Data frame(Data=Data)
df

In the example above, we have two columns. The first column contains date values ​​of type datetime.date and the other contains time values ​​of type datetime.time.

To combine them, we can do:

1
2
3
4
5

# combine them into strings
new_df = pd.to_datetime(df.Appointment.astype(chain) + ‘ ‘ +df.time.astype(chain))
# add a column to the dataframe
df.insert(2, ‘date hour’, new_df)
df

We convert columns to string type and concatenate them using addition operator in Python.

We then insert the resulting column into the existing dataframe using the insert method. This should return the DataFrame as shown:

Conclusion

This article explained how you can combine date and time objects in Pandas to create a timestamp object. We also explained how to combine date and time columns.

Leave a Reply

Your email address will not be published.