1

Lets say I have following DataFrame:

import pandas as pd
df = pd.DataFrame({"Date":["2022-01-01", "2022-01-02", "2022-01-03"], "Time":[0,1,10]})

I want another column which is a datetime using the Date and the Time Columns.

Expected result

         Date  Time            DateTime
0  2022-01-01     0 2022-01-01 00:00:00
1  2022-01-02     1 2022-01-02 01:00:00
2  2022-01-03    10 2022-01-03 10:00:00

Trial

I tried this failed solution:

df["DateTime"] = str(df["Date"]) + " " + str(df["Time"]) + ":00"

Which outputs:

>>> df
         Date  Time                                           DateTime
0  2022-01-01     0  0    2022-01-01\n1    2022-01-02\n2    2022-01...
1  2022-01-02     1  0    2022-01-01\n1    2022-01-02\n2    2022-01...
2  2022-01-03    10  0    2022-01-01\n1    2022-01-02\n2    2022-01...

3 Answers 3

2

You can just do Date and Time add with to_datetime and to_timedelta

df['new'] = pd.to_datetime(df['Date']) + pd.to_timedelta(df['Time'],unit='hour')
df
Out[388]: 
         Date  Time                 new
0  2022-01-01     0 2022-01-01 00:00:00
1  2022-01-02     1 2022-01-02 01:00:00
2  2022-01-03    10 2022-01-03 10:00:00
Sign up to request clarification or add additional context in comments.

1 Comment

How to do this if I have date as 'DD.MM.YYY' and time as 'HH:MM:SS', both are just objects?
0

One solution would be the following:

df["DateTime"] = df["Date"].astype(str) + " " + df["Time"].astype(str) + ":00"

Then convert to datetime:

df["DateTime"] = pd.to_datetime(df["DateTime"])

Hence the output is as expected:

>>> df
         Date  Time            DateTime
0  2022-01-01     0 2022-01-01 00:00:00
1  2022-01-02     1 2022-01-02 01:00:00
2  2022-01-03    10 2022-01-03 10:00:00

Comments

0
df['date'] = [d.date() for d in df['datetime']]
df['time'] = [d.time() for d in df['datetime']]
df['date']= pd.to_datetime(df['date'])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.