Parse date string and change format

后端 未结 9 871
孤街浪徒
孤街浪徒 2020-11-22 00:58

I have a date string with the format \'Mon Feb 15 2010\'. I want to change the format to \'15/02/2010\'. How can I do this?

9条回答
  •  我寻月下人不归
    2020-11-22 01:51

    You may achieve this using pandas as well:

    import pandas as pd
    
    pd.to_datetime('Mon Feb 15 2010', format='%a %b %d %Y').strftime('%d/%m/%Y')
    

    Output:

    '15/02/2010'
    

    You may apply pandas approach for different datatypes as:

    import pandas as pd
    import numpy as np
    
    def reformat_date(date_string, old_format, new_format):
        return pd.to_datetime(date_string, format=old_format, errors='ignore').strftime(new_format)
    
    date_string = 'Mon Feb 15 2010'
    date_list = ['Mon Feb 15 2010', 'Wed Feb 17 2010']
    date_array = np.array(date_list)
    date_series = pd.Series(date_list)
    
    old_format = '%a %b %d %Y'
    new_format = '%d/%m/%Y'
    
    print(reformat_date(date_string, old_format, new_format))
    print(reformat_date(date_list, old_format, new_format).values)
    print(reformat_date(date_array, old_format, new_format).values)
    print(date_series.apply(lambda x: reformat_date(x, old_format, new_format)).values)
    

    Output:

    15/02/2010
    ['15/02/2010' '17/02/2010']
    ['15/02/2010' '17/02/2010']
    ['15/02/2010' '17/02/2010']
    

提交回复
热议问题