Skip to content Skip to sidebar Skip to footer

Return Pandas Df Column With The Number Of Days Elapsed Between Index And Today's Date

I have a dF that has dates as its index, and I would like to add a new column 'delta' that shows the number of days between the date in the index and todays date. I have: dF['today

Solution 1:

You can use pandas methods to solve the problem right away.

Consider e.g.

df = pd.DataFrame({'A' : [1,2,3]}
      , index = [pd.to_datetime(['2015-01-30', '2015-01-29','2015-01-25'])] )

that is

A2015-01-30  12015-01-29  22015-01-25  3

then you define

today = pd.to_datetime('2015-01-30')

so that you can finally calculate

(df.index - today).daysarray([ 0, -1, -5])

which clearly can be added as a further column.


Finally, the date of today can be obtained automatically by doing

today = pd.datetime.today()

Solution 2:

import time
import datetime

def ymd2epoch(y, m, d):
    t = datetime.datetime(y, m, d, 0, 0, 0).timetuple()
    return int(time.mktime(t))

def yyyymmdd2epoch(s):
    ymd = map(int, s.split('-'))
    return ymd2epoch(ymd[0], ymd[1], ymd[2])

def ymd_todaydiff(ymd):
    seconds_diff = int(time.time()) - yyyymmdd2epoch(ymd)
    daydiff = seconds_diff / (24*60*60)
    return daydiff

if __name__ == '__main__':
    import sys

    for ymd in sys.argv[1:]:
        sys.stdout.write("DayDiff(%s) = %d\n" % 
                         (ymd, ymd_todaydiff(ymd)))
    sys.exit(0)

running it:

$./daydiff.py2015-01-01 2015-01-29 2015-01-30 2014-01-30DayDiff(2015-01-01)=30DayDiff(2015-01-29)=2DayDiff(2015-01-30)=1DayDiff(2014-01-30)=366

Post a Comment for "Return Pandas Df Column With The Number Of Days Elapsed Between Index And Today's Date"