Home > front end >  Pandas not adding time when converting string to datetime
Pandas not adding time when converting string to datetime

Time:09-17

I'm trying to convert a string to date using pandas, but can't figure out how to also get time (00:00:00) added.

I have a column named "Date" with the following string formatting: YYYY-MM-DD

python code:

import pandas as pd
datetime = pd.to_datetime(data_frame[DATE])

Printing datetime or exporting it as csv shows only the date, without time:

0       2021-09-01
1       2021-09-01
2       2021-09-01
3       2021-09-01
4       2021-09-01

However, the expected result YYY-MM-DD hh:mm:ss shows up if I only print one value at a time:

print(datetime[0])

Outputs: 2021-09-01 00:00:00

CodePudding user response:

You can use strftime to convert as a string of your choice:

df['DATE'] = pd.to_datetime(df['DATE'])
df['DATE'] = df['DATE'].dt.strftime('%Y-%m-%d %H:%M:%S')
df.to_csv('filename.csv')

output:

                  DATE
0  2021-09-01 00:00:00
1  2021-09-01 00:00:00
2  2021-09-01 00:00:00
3  2021-09-01 00:00:00
4  2021-09-01 00:00:00
  • Related