Skip to content

Instantly share code, notes, and snippets.

@vikramsoni2
Last active January 21, 2019 12:30
Show Gist options
  • Save vikramsoni2/b672f3789f8468279fc6705f15522342 to your computer and use it in GitHub Desktop.
Save vikramsoni2/b672f3789f8468279fc6705f15522342 to your computer and use it in GitHub Desktop.
def add_datepart(df, fldname, drop=True):
fld = df[fldname]
if not np.issubdtype(fld.dtype, np.datetime64):
df[fldname] = fld = pd.to_datetime(fld, infer_datetime_format=True)
targ_pre = re.sub('[Dd]ate$', '', fldname)
for n in ('Year', 'Month', 'Week', 'Day', 'Dayofweek', 'Dayofyear',
'Is_month_end', 'Is_month_start', 'Is_quarter_end', 'Is_quarter_start', 'Is_year_end', 'Is_year_start'):
df[targ_pre+n] = getattr(fld.dt,n.lower())
df[targ_pre+'Elapsed'] = fld.astype(np.int64) // 10**9
if drop: df.drop(fldname, axis=1, inplace=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment