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]:
DatetimeIndex(['2016-01-31', '2016-02-29', '2016-03-31', '2016-04-30',
               '2016-05-31', '2016-06-30', '2016-07-31', '2016-08-31',
               '2016-09-30', '2016-10-31', '2016-11-30', '2016-12-31',
               '2017-01-31', '2017-02-28', '2017-03-31', '2017-04-30',
               '2017-05-31', '2017-06-30', '2017-07-31', '2017-08-31',
               '2017-09-30', '2017-10-31', '2017-11-30', '2017-12-31',
               '2018-01-31', '2018-02-28', '2018-03-31', '2018-04-30',
               '2018-05-31', '2018-06-30', '2018-07-31', '2018-08-31',
               '2018-09-30', '2018-10-31', '2018-11-30', '2018-12-31'],
              dtype='datetime64[ns]', freq='M')
In [3]:
# use datetime index as "date" columns 
df = pd.DataFrame(data={'date': date_rng})
df.head()
Out[3]:
date
0 2016-01-31
1 2016-02-29
2 2016-03-31
3 2016-04-30
4 2016-05-31

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]:
date date_add
0 2016-01-31 2016-02-10
1 2016-02-29 2016-03-10
2 2016-03-31 2016-04-10
3 2016-04-30 2016-05-10
4 2016-05-31 2016-06-10
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]:
date date_add date_subtract
0 2016-01-31 2016-02-10 2016-01-21
1 2016-02-29 2016-03-10 2016-02-19
2 2016-03-31 2016-04-10 2016-03-21
3 2016-04-30 2016-05-10 2016-04-20
4 2016-05-31 2016-06-10 2016-05-21

Comments

Comments powered by Disqus