Python Forum
pandas.to_datetime: Combine data from 2 columns - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Data Science (https://python-forum.io/forum-44.html)
+--- Thread: pandas.to_datetime: Combine data from 2 columns (/thread-32599.html)



pandas.to_datetime: Combine data from 2 columns - ju21878436312 - Feb-20-2021

I would like to combine data from 2 columns

The file "minimal_in.csv" is the following:

Year,Time
29.01.2001,13:31:24
29.01.2001,13:31:27
29.01.2001,13:31:29
29.01.2001,13:31:32
29.01.2001,13:31:34
I have first tried:

import pandas as pd
from datetime import datetime, timedelta

import pandas as pd

df = pd.read_csv('minimal_in.csv')
df.head(5)

df[['Year','Time']].apply(pd.to_datetime)
df.dtypes
or alternatively:

df_combine = df['Year','Time']
pd.to_datetime(df_combine)
Has someone an idea? I would be very grateful Smile


RE: pandas.to_datetime: Combine data from 2 columns - perfringo - Feb-20-2021

Something like below?

import pandas as pd

df = pd.read_csv('minimal_in.csv')

df['Datetime'] = pd.to_datetime(df['Year'] + df['Time'], format='%d.%m.%Y%H:%M:%S')
df will look like:

Output:
Year Time Datetime 0 29.01.2001 13:31:24 2001-01-29 13:31:24 1 29.01.2001 13:31:27 2001-01-29 13:31:27 2 29.01.2001 13:31:29 2001-01-29 13:31:29 3 29.01.2001 13:31:32 2001-01-29 13:31:32 4 29.01.2001 13:31:34 2001-01-29 13:31:34