Search code examples
pandasdataframedate-conversionstring-to-datetime

pandas dataframe converting complex date-format to date dd/mm/yyyy hh:mm


I'm using python and pandas to transform csv's, I imported the csv as a dataframe.

the dataframe has a string-column containing dates in format "January 1, 2016, Hour 0"

I'd like to convert that string into a date or even string in format dd/mm/yyyy hh:mm

note that in this case the minutes will always be 0.

thanks !


Solution

  • I've done it using datetime and strptime as following

    df['field'].apply(lambda x : datetime.strptime(x, '%B %d, %Y, Hour %H').strftime('%d/%m/%Y %H:00'))
    

    or generally:

    df['field'].apply(lambda x : datetime.strptime(x, old_formatted_date).strftime(new_formatted_date))
    

    for more on datetime default lib check: datetime

    and datetime format codes: datetime format codes