Search code examples
pythonpandasdatetimedatetime-formatpython-datetime

Convert date in dataframe


I have a data frame which is of the stop and search of the police in London; the 'date' column has entries like the 2019-10-01T04:31:39+00:00 2019-10-01T04:31:39+.. in each row I'm trying to extract day month and year to be able to begin analysis.

Could anyone please assist me in doing this??


Solution

  • Take a look at how datetime strings are converted to date (or date time) objects in python. For your scenario apply a function to the whole column of date strings that you reading from source.

    def convert_str_to_date(date_string):
        converted_date = datetime.strptime(date_string, "%Y-%m-%dT%H:%M:%S%z")
        return converted_date.month, converted_date.day, converted_date.year
    
    
    >>> df
             name_of_date_column
    0  2019-10-01T04:31:39+00:00
    1  2019-10-01T04:31:39+00:00
    
    df.apply(lambda x: convert_str_to_date(x['name_of_date_column']), axis=1)
    # 0    (10, 1, 2019)
    # 1    (10, 1, 2019)
    # dtype: object
    

    The first line of this function is doing the work of converting string to respective elements of datetime.