Alex
Alex

Reputation: 1131

convert mixed date with int and string to date

i have a dataframe with a column of dates. the date format is "mixed" with integers and string, like: " 15 January 2000". i would like to have a column with a date like "2000-01-15"

list_dates = ['15 January 2000', '16 January 2000', '17 January 2000']
df_dates = pd.DataFrame(list_dates)

df_dates['expect'] = ['2000-01-15', '2000-01-16', '2000-01-17']

I expect a column like "df_dates['expect']". Thank you for help!

Upvotes: 0

Views: 381

Answers (3)

Nk03
Nk03

Reputation: 14949

Here's one way:

df_dates['expect'] = pd.to_datetime(df_dates['date'])

Upvotes: 2

Animikh Aich
Animikh Aich

Reputation: 647

A simple solution would be to use pandas.to_datetime function.

You are looking for the function:

df_dates["expect"] = pd.to_datetime(df_dates["column_name"])

A code snippet is shown below:

import pandas as pd

list_dates = ['15 January 2000', '16 January 2000', '17 January 2000']
df_dates = pd.DataFrame(list_dates)
df_dates['expect'] = pd.to_datetime(df_dates[0])
print(df_dates)

Output:

                 0     expect
0  15 January 2000 2000-01-15
1  16 January 2000 2000-01-16
2  17 January 2000 2000-01-17

Upvotes: 1

sehan2
sehan2

Reputation: 1835

Here you go:

from datetime import datetime

new_values = []
for d in df_dates[0].values:
    dt = datetime.strptime(d, '%d %B %Y')
    new_values.append(f'{dt.year}-{dt.month}-{dt.day}')
df_dates[0] = new_values

Upvotes: 1

Related Questions