Adding Or Substracting Time
Goal¶
This post aims to add or subtract time from date column using pandas:
- Pandas
Reference:
- Chris Albon's blog (I look at his post's title and wrote my own contents to deepen my understanding about the topic.)
Library¶
In [1]:
import pandas as pd
Create date columns using date_range¶
In [2]:
date_rng = pd.date_range(start='20160101', end='20190101', freq='m', closed='left')
date_rng
Out[2]:
In [3]:
# use datetime index as "date" columns
df = pd.DataFrame(data={'date': date_rng})
df.head()
Out[3]:
Add days from date columns¶
In [4]:
days_add = 10 # days
df.loc[:, 'date_add'] = df.loc[:, 'date'] + pd.Timedelta(value=days_add, unit='d')
df.head()
Out[4]:
In [5]:
# Subtract days from date columns
df.loc[:, 'date_subtract'] = df.loc[:, 'date'] - pd.Timedelta(value=days_add, unit='d')
df.head()
Out[5]:
Comments
Comments powered by Disqus