df['date'] is the column I am working with.
The data is in the 'date' column is in the day/month/year format, like this: 7/12/2019. How would I modify this column to give me Year-month-day, or 2019-07-12?
This is what I have tried, but still is not working: df['date'] = pd.to_datetime(str(df['date']))
Try:
df.loc[:,'date'] = pd.to_datetime(df.loc[:,'date'], format="%d/%m/%yyyy")
Let me know if it works!
EDIT #1
Since, the "date" column has mixed formats, try:
def date_format(df):
for index, row in df.iterrows():
try:
df.loc[index, row['date']] = pd.to_datetime(df.loc[index, row['date']], format="%d/%m/%yyyy")
except ValueError as e:
df.loc[index, row['date']] = pd.to_datetime(df.loc[index, row['date']], format="%m/%d/%yyyy")
return df
You can use dt.strftime if you need to convert datetime
to other formats (but note that then dtype of column will be object
( string
)):
import pandas as pd
df = pd.DataFrame({'DOB': {0: '26/1/2016', 1: '26/1/2016'}})
print (df)
DOB
0 26/1/2016
1 26/1/2016
df['DOB'] = pd.to_datetime(df.DOB)
print (df)
DOB
0 2016-01-26
1 2016-01-26
df['DOB1'] = df['DOB'].dt.strftime('%m/%d/%Y')
print (df)
DOB DOB1
0 2016-01-26 01/26/2016
1 2016-01-26 01/26/2016
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.