1

With this program code

df['forecast_day'] =  pd.to_datetime(df['forecast_day'], format='%Y%m%d')
df['forecast_time'] = pd.to_datetime(df['forecast_time'], format='%H%M')

My current columns of date and time in DataFrame look like this.

    forecast_day        forecast_time
0   2021-05-05 00:00:00 1900-01-01 12:00:00
1   2021-05-05 00:00:00 1900-01-01 11:00:00
2   2021-05-05 00:00:00 1900-01-01 10:00:00
3   2021-05-05 00:00:00 1900-01-01 09:00:00
4   2021-05-05 00:00:00 1900-01-01 08:00:00
5   2021-05-05 00:00:00 1900-01-01 07:00:00
6   2021-05-05 00:00:00 1900-01-01 06:00:00
7   2021-05-05 00:00:00 1900-01-01 05:00:00
8   2021-05-05 00:00:00 1900-01-01 04:00:00
9   2021-05-05 00:00:00 1900-01-01 03:00:00
10  2021-05-05 00:00:00 1900-01-01 02:00:00

The combined column should look like:

    forecast_day&time       
0   2021-05-05 12:00:00
1   2021-05-05 11:00:00
2   2021-05-05 10:00:00
3   2021-05-05 09:00:00
4   2021-05-05 08:00:00
5   2021-05-05 07:00:00
6   2021-05-05 06:00:00
7   2021-05-05 05:00:00
8   2021-05-05 04:00:00
9   2021-05-05 03:00:00
10  2021-05-05 02:00:00

Roim
  • 2,986
  • 2
  • 10
  • 25
  • 3
    Does this answer your question? [Combine Date and Time columns using python pandas](https://stackoverflow.com/questions/17978092/combine-date-and-time-columns-using-python-pandas) – Roim May 22 '21 at 11:29
  • With this code pd.to_datetime(df['forecast_day'] + ' ' + df['forecast_time']) I got an error like unsupported operand type(s) for +: 'DatetimeArray' and 'str' – Chirayu Ball May 22 '21 at 11:33
  • since you already convertedboth columns to datetime so use `pd.to_datetime(df['forecast_day'].astype(str)+' '+df['forecast_time'].dt.time.astype(str))` – Anurag Dabas May 22 '21 at 11:38

1 Answers1

0

Take the dates and times from the respective columns, add them after converting them to strings and then convert the entire column to the datetime type,

df['new_column'] = pd.to_datetime(df.apply(lambda x: str(x['forecast_day'].date()) + " " + str(x['forecast_time'].time()), axis=1))
Minura Punchihewa
  • 1,498
  • 1
  • 12
  • 35