Search code examples
pythonpython-3.xpandasdatetimestrptime

how to change datetimeindex to just contain date in python


I have a column called date with this values

> DatetimeIndex(['2014-02-19'], dtype='datetime64[ns]', freq=None)
> DatetimeIndex(['2013-02-29'], dtype='datetime64[ns]', freq=None)
> DatetimeIndex(['2018-04-15'], dtype='datetime64[ns]', freq=None)

how do i modify the column to just extract the date values and get rid of words like DatetimeIndex and brackets etc?

> 2014-02-19
> 2013-02-19
> 2018-04-15
 

The code I wrote I think is pretty incorrect but still attaching it here:

def fundate(x):
    return x[0][0]

df['date'] = df.apply(lambda row : fundate(row['date']), axis = 1)

could someone please help me?


Solution

  • If there is object DatetimeIndex use:

    df['date'] = df['date'].str[0]
    

    If there is multiple values per row:

    df = df.explode('date')
    

    If there are strings and only one value per row:

    df["date"] = df["date"].str.extract(r"(\d{4}-\d{2}-\d{2})", expand=False)
    

    If possible multiple values per row:

    df["date"] = df["date"].str.findall(r"(\d{4}-\d{2}-\d{2})")
    df = df.explode('date')