0

Hello every one i am trying to convert date. I have this ' January 7, 2018' type of date and i am trying to change the date format in 01-07-2018 or 07-01-2018 i am trying to covert the date. but not converted.

from datetime import datetime
df3 = df2.copy()
df3["Last Updated"] = [datetime.strptime(i, '%B %d, %Y') for i in df3["Last Updated"]]

i am trying this way to convert the date but not successful if you know the proper way or any mistake in my code so inform me or help me to solve the error.

enter image description here

FObersteiner
  • 22,500
  • 8
  • 42
  • 72
user12498867
  • 1
  • 1
  • 3
  • 1
    Does this answer your question? [Convert DataFrame column type from string to datetime, dd/mm/yyyy format](https://stackoverflow.com/questions/17134716/convert-dataframe-column-type-from-string-to-datetime-dd-mm-yyyy-format) – Joe Jun 22 '20 at 05:02

2 Answers2

0

Try converting the column to datetime first

df3['Last Updated'] = pd.to_datetime(df3['Last Updated'])
df3["Last Updated"] = [datetime.strptime(i, '%B %d, %Y') for i in df3["Last Updated"]]
Biranchi
  • 16,120
  • 23
  • 124
  • 161
  • i am trying your suggesstion .give me error as "day is out of range for month" – user12498867 Jun 22 '20 at 03:06
  • your second line makes no sense at all - the first one should simply be `df3['Last Updated'] = pd.to_datetime(df3['Last Updated'], format='%B %d, %Y')` – FObersteiner Jun 22 '20 at 06:00
  • Yes this is fine, it can be done in a single line. I had added just to make it simple and not confuse with the existing code. It's easy to debug that way. – Biranchi Jun 22 '20 at 15:19
0

I have tried replicating the dataset below:

import pandas as pd
from datetime import datetime

data = pd.DataFrame({'App':['a','b'],'Category':['Art&Design','Art&Design'],'Date':['January 7, 2018', 'January 8, 2018']})
data['Date'] = pd.to_datetime(data['Date']).dt.strftime('%d-%m-%Y')
print(data)
Dwight
  • 124
  • 2
  • 12