Home > Back-end >  how to convert date format in a dataframe
how to convert date format in a dataframe

Time:05-17

I have a data frame that contains the information below :

N_Ord   PSN      debut_interval
1      A4BA0D07  01/01/2022
2      04BB0607  01/01/2022

I need to

  • convert the debut_interval of each row of my dataframe to that format yyyy-mm-ddT00:00:00
  • add a new column fin_interval that contains the same date like that yyyy-mm-ddT23:59:59

CodePudding user response:

You can use:

fmt = '%Y-%m-%dT%H:%M:%S'
df2 = (df
  .assign(debut_interval=pd.to_datetime(df['debut_interval'], dayfirst=True),
          fin_interval=lambda d: d['debut_interval'].add(pd.to_timedelta('23:59:59')).dt.strftime(fmt))
  .assign(debut_interval=lambda d: d['debut_interval'].dt.strftime(fmt)
          )
       )

Output:

   N_Ord       PSN       debut_interval         fin_interval
0      1  A4BA0D07  2022-01-01T00:00:00  2022-01-01T23:59:59
1      2  04BB0607  2022-01-01T00:00:00  2022-01-01T23:59:59

CodePudding user response:

def get_date(fmt):
    fmt = "%Y-%m-%dT"   fmt
    return lambda x: x.dt.strftime(fmt)

df['debut_interval'] = pd.to_datetime(df['debut_interval'])
df.debut_interval.transform({'debut_interval':get_date('00:00:00'),
                            'fin_interval':get_date('23:59:59')})
 
        debut_interval         fin_interval
0  2022-01-01T00:00:00  2022-01-01T23:59:59
1  2022-01-01T00:00:00  2022-01-01T23:59:59
  • Related