Listado de la etiqueta: 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:

1

Timestamp.combine(date, time)

The function accepts two main parameters:

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

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

Example

An example is shown in the example below:

1
2
3
4
5
6

# import pandas
import pandas as pd
# import date and time
from datetime import date, time
ts = pd.Timestamp.combine(date(2022,4,11), time(13,13,13))
print(ts)

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:

1
2
3
4
5

# import pandas
# from datetime import date, time
data = {‘dates’: [date(2022,4,11), date(2023,4,11)], ‘time’: [time(13,13,13), time(14,14,14)]}
df = pd.DataFrame(data=data)
df

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:

1
2
3
4
5

# combine them as strings
new_df = pd.to_datetime(df.dates.astype(str) + ‘ ‘ +df.time.astype(str))
# add column to dataframe
df.insert(2, ‘datetime’, new_df)
df

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:

Conclusion

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.



Source link