Search code examples
pythonpandasdataframedateobject

Remove eveything after a specifc number in Date column


I have a column in a data frame with Date in below format 2016-01-13 00:00:00 The abovecolumn is in object datatype format.

While I run the code I need to get answer as 2016-01-13 Without time in it.

what would be the easiest way to accomplish this?


Solution

  • You may use the datetime module to get rid of the time component from a date column. Maybe try this:

    from datetime import datetime
    
    # Assuming your date column is named 'Date' in the DataFrame df
    df['Date'] = pd.to_datetime(df['Date'])  # Convert the column to datetime type
    df['Date'] = df['Date'].dt.date  # Extract only the date portion
    
    # If you want to convert the column back to string format
    df['Date'] = df['Date'].astype(str)
    

    The 'Date' column is first converted to datetime format using pd.to_datetime(). Then, we take the date component of the datetime object and extract it using the .dt.date attribute. Finally, you may use .astype(str) to return the column to its original string format.

    Please be sure to change 'Date' to the correct name of your date column in the DataFrame.