Alsphere
Alsphere

Reputation: 533

How can I insert datetime into dataframe using panda python

I have csv data as below:

x    y    date    time
2    4    4/5/2017 00:22:34
5    1    4/5/2017 00:22:50
.    .    ......    ......
.    .    .....      .....
so on

I converted date and time into one single datetime column and I want to insert that datetime back again into csv file or into dataframe.

output:

x    y    datetime
2    4    4-5-2017 00:22:34

I tried this code:

import pandas as pd
df = pd.read_csv('file.csv')
datetime = pd.to_datetime(df['date'] + ' ' + df['time'])
print(datetime)

I want to insert datetime to the df in order to write it to the csv file.

Upvotes: 0

Views: 4765

Answers (1)

MaxU - stand with Ukraine
MaxU - stand with Ukraine

Reputation: 210852

Try this:

df['datetime'] = pd.to_datetime(df.pop('date') + ' ' + df.pop('time'))

or do it on the fly:

In [51]: pd.read_csv(filename, delim_whitespace=True,
                     parse_dates={'datetime':['date','time']})
Out[51]:
             datetime  x  y
0 2017-04-05 00:22:34  2  4
1 2017-04-05 00:22:50  5  1

Upvotes: 3

Related Questions