Search code examples
python-3.xpandaspython-datetime

Pandas specify which columns to use in datetime


I have a pandas dataframe df:

df = pd.DataFrame({'year': [2018, 2018,2018,2018,2018,2018],
                   'month': [8, 8,8,8,8,8],
                   'day': [3,3,3,3,3,3],
                   'hour': [11, 12,12,9,7,2],                   
                   'minute': [00, 00,00,00,00,00],                                      
                   'second': [0, 0,0,0,0,0]})
df['X'] = [3,5,4,1,8,2]

I then specify a list of attributes required to convert to datetime (which match some,but not per se all, of the column names in df): L = ['year', 'month', 'day', 'hour', 'minute', 'second'] How do I then get a datetime column based on the the attributes specified in the list L?


Solution

  • Filter columns by list and pass to to_datetime:

    df['dates'] = pd.to_datetime(df[L])
    print (df)
       year  month  day  hour  minute  second  X               dates
    0  2018      8    3    11       0       0  3 2018-08-03 11:00:00
    1  2018      8    3    12       0       0  5 2018-08-03 12:00:00
    2  2018      8    3    12       0       0  4 2018-08-03 12:00:00
    3  2018      8    3     9       0       0  1 2018-08-03 09:00:00
    4  2018      8    3     7       0       0  8 2018-08-03 07:00:00
    5  2018      8    3     2       0       0  2 2018-08-03 02:00:00