Pandas Combine Date and Time
This short article will discuss how you can create a Pandas timestamp object by combining date and time strings.
Pandas Combine() Function
Pandas provide us with the timestamp.combine() function which allows us to take a date and time string values and combine them to a single Pandas timestamp object.
The function syntax is as shown below:
The function accepts two main parameters:
- Date – refers to the datetime.date object denoting the date string.
- Time – specifies the datetime.time object.
The function returns the timestamp objected from the date and time parameters passed.
An example is shown in the example below:
We use the date and time functions from 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 shown below:
In the example above, we have two columns. The first column holds date values of type datetime.date and the other holds time values of type datetime.time.
To combine them, we can do:
We convert the columns to string type and concatenate them using the 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:
This article discussed how you could combine date and time objects in Pandas to create a timestamp object. We also covered how you can combine date and time columns.