Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert time object to datetime format in python pandas

I have a dataset of column name DateTime having dtype object.

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

I have used the above code to convert to datetime format then did a split in the column to have Date and Time separately

df['date'] = df['DateTime'].dt.date
df['time'] = df['DateTime'].dt.time

but after the split the format changes to object type and while converting it to datetime it showing error for the time column name as: TypeError: is not convertible to datetime

How to convert it to datetime format the time column

like image 545
Nadeem Haque Avatar asked Nov 25 '18 17:11

Nadeem Haque


People also ask

How do I change time format in pandas?

Function usedstrftime() can change the date format in python.

How do you change the datatype of an object to a date in python?

The date column is indeed a string, which—remember—is denoted as an object type in Python. You can convert it to the datetime type with the . to_datetime() method in pandas .

How do you convert an object to time in python?

Pandas to_datetime() method helps to convert string Date time into Python Date time object. Parameters: arg: An integer, string, float, list or dict object to convert in to Date time object. dayfirst: Boolean value, places day first if True.


1 Answers

You can use combine in list comprehension with zip:

df = pd.DataFrame({'DateTime': ['2011-01-01 12:48:20', '2014-01-01 12:30:45']})
df['DateTime'] = pd.to_datetime(df['DateTime'])

df['date'] = df['DateTime'].dt.date
df['time'] = df['DateTime'].dt.time

import datetime
df['new'] = [datetime.datetime.combine(a, b) for a, b in zip(df['date'], df['time'])]
print (df)

             DateTime        date      time                 new
0 2011-01-01 12:48:20  2011-01-01  12:48:20 2011-01-01 12:48:20
1 2014-01-01 12:30:45  2014-01-01  12:30:45 2014-01-01 12:30:45

Or convert to strings, join together and convert again:

df['new'] = pd.to_datetime(df['date'].astype(str) + ' ' +df['time'].astype(str))
print (df)
             DateTime        date      time                 new
0 2011-01-01 12:48:20  2011-01-01  12:48:20 2011-01-01 12:48:20
1 2014-01-01 12:30:45  2014-01-01  12:30:45 2014-01-01 12:30:45

But if use floor for remove times with converting times to timedeltas then use + only:

df['date'] = df['DateTime'].dt.floor('d')
df['time'] = pd.to_timedelta(df['DateTime'].dt.strftime('%H:%M:%S'))

df['new'] = df['date'] + df['time']
print (df)

             DateTime       date     time                 new
0 2011-01-01 12:48:20 2011-01-01 12:48:20 2011-01-01 12:48:20
1 2014-01-01 12:30:45 2014-01-01 12:30:45 2014-01-01 12:30:45
like image 152
jezrael Avatar answered Sep 30 '22 11:09

jezrael