How to make two different date format in single column unique?

后端 未结 3 818
隐瞒了意图╮
隐瞒了意图╮ 2020-12-22 03:36

I have one column in I don\'t understand how but there is two different format in a single column.

df[\'Date\'] = [6/24/2019,6/14/2019,2019-09-06 00:00:00,6/         


        
相关标签:
3条回答
  • 2020-12-22 04:14

    Try importing the datetime class. This will allow you to use the strptime function like below:

    format = '%d/%m/%Y'
    data['New_date'] = datetime.strptime('2019-09-06 00:00:00', format)
    
    0 讨论(0)
  • 2020-12-22 04:15
    import pandas as pd
    df = pd.DataFrame()
    df['Date'] = ['6/24/2019','6/14/2019','2019-09-06 00:00:00','6/14/2019','6/14/2019']
    df['newDate'] = pd.to_datetime(df['Date'])
    print (df)
    
                      Date    newDate
    0            6/24/2019 2019-06-24
    1            6/14/2019 2019-06-14
    2  2019-09-06 00:00:00 2019-09-06
    3            6/14/2019 2019-06-14
    4            6/14/2019 2019-06-14
    
    0 讨论(0)
  • 2020-12-22 04:25

    Use to_datetime with both formats and errors='coerce' for NaT if not match and replace missing values by another Series by Series.combine_first or Series.fillna them, last convert to strings by Series.dt.strftime:

    s1 = pd.to_datetime(data['Date'], format='%Y-%d-%m %H:%M:%S', errors='coerce')
    s2 = pd.to_datetime(data['Date'], format = '%m/%d/%Y', errors='coerce')
    
    #2 possible solutions
    data['new'] = s1.fillna(s2).dt.strftime('%m/%d/%Y')
    data['new'] = s1.combine_first(s2).dt.strftime('%m/%d/%Y')
    print (data)
                      Date         new
    0            6/24/2019  06/24/2019
    1            6/14/2019  06/14/2019
    2  2019-09-06 00:00:00  06/09/2019
    3            6/14/2019  06/14/2019
    4            6/14/2019  06/14/2019
    
    0 讨论(0)
提交回复
热议问题