Converting date between DD/MM/YYYY and YYYY-MM-DD?

前端 未结 6 1980
隐瞒了意图╮
隐瞒了意图╮ 2020-12-23 16:24

Using a Python script, I need to read a CVS file where dates are formated as DD/MM/YYYY, and convert them to YYYY-MM-DD before saving this into a SQLite database.

Th

6条回答
  •  清歌不尽
    2020-12-23 16:58

    In case you need to convert an entire column of data (from pandas DataFrame), then first convert it (pandas Series) to the datetime format using to_datetime and finally use .dt.strftime:

    def conv_dates_series(df, col, old_date_format, new_date_format):
    
        df[col] = pd.to_datetime(df[col], format=old_date_format).dt.strftime(new_date_format)
    
        return(df)
    
    

    Sample usage:

    import pandas as pd
    
    test_df = pd.DataFrame({"Dates": ["1900-01-01", "1999-12-31"]})
    
    old_date_format='%d/%m/%Y'
    new_date_format='%Y-%m-%d'
    
    conv_dates_series(test_df, "Dates", old_date_format, new_date_format)
    

提交回复
热议问题