user1955215
user1955215

Reputation: 743

Date and time conversion in python pandas

A .csv file has a date column. When read into a pandas DataFrame and displayed, the date and time are displayed as:

2021-06-30 19:39:25 

The correct date is 30-06-2021 19:39:25

How can this be changed?

Upvotes: 1

Views: 710

Answers (3)

Karn Kumar
Karn Kumar

Reputation: 8816

try below:

df = pd.DataFrame({'Date':['2021-06-30 19:39:25', '2021-07-22 19:39:25', '2021-08-18 19:39:25']})
# convert `Date` column to datetime
df['Date'] = pd.to_datetime(df['Date'])

Solution:

 df['Date'] = pd.to_datetime(df['Date'] , format = '%d-%m-%Y %H:%M:%S')

 if the above doesn't work then use belwo..

# Now convert to desired format
df['Date'] = pd.to_datetime(df["Date"].dt.strftime('%m-%d-%Y %H:%M:%S')).dt.strftime('%d-%m-%Y %H:%M:%S')
print(df)
0    30-06-2021 19:39:25
1    22-07-2021 19:39:25
2    18-08-2021 19:39:25
Name: Date, dtype: object

Upvotes: 1

Pavan Suvarna
Pavan Suvarna

Reputation: 501

using pandas.to_datetime method to convert date format will be more reliable

df['Date'] = pd.to_datetime(df['Date'] , format = '%d-%m-%Y %H:%M:%S')

Upvotes: 1

U13-Forward
U13-Forward

Reputation: 71580

Try strftime:

>>> date.strftime('%d-%m-%Y %H:%M:%S')
'30-06-2021 19:39:25'
>>> 

Upvotes: 1

Related Questions