pythonpandasdataframedatetime

Create datetime object, accounting for possible next day


I am processing data from a form. I have imported the data as a dataframe.

The form has an initial date and time that have been converted into a datetime object. Partway through the form is a second time that is stored as a time object.

I wish to create a datetime object for the second time. However, the date may be the next day.

For instance, if the initial date was 2025-1-1 and the time was 10:25 PM, and the next time was 01:25 AM I wish to create a datetime for 2025-1-2 at 1:25 AM.

Is there a straightforward way to do this within a dataframe?

Example (not in a dataframe):

initialDate = date(2025, 1, 1)
initialTime = time(22, 25)
initialDatetime = datetime(2025, 1, 1, 22, 25)
secondTime = time(1, 25)

Solution

  • If your requirement is that secondDateTime must be later than initialDateTime, use a condition to add 1 day to secondDateTime:

    df = pd.DataFrame({
        "initialDate": ["2025-1-1"],
        "initialTime": ["10:25 PM"],
        "secondTime": ["1:25 AM"]
    })
    
    d1 = pd.to_datetime(df["initialDate"] + " " + df["initialTime"])
    d2 = pd.to_datetime(df["initialDate"] + " " + df["secondTime"])
    df["initialDateTime"] = d1
    df["secondDateTime"] = d2 + pd.to_timedelta(np.where(d2 < d1, 1, 0), unit="d")