How to find the date n days ago in Python?

Dirty_Fox picture Dirty_Fox · Feb 1, 2015 · Viewed 32.3k times · Source

Good evening chaps,

I would like to write a script where I give python a number of days (let s call it d) and it gives me the date we were d days ago.

I am struggling with the module datetime:

import datetime 

tod = datetime.datetime.now()
d = timedelta(days = 50) 
a = tod - h 
Type Error : unsupported operand type for - : "datetime.timedelta" and 
"datetime.datetime" 

Thanks for your help

Answer

Padraic Cunningham picture Padraic Cunningham · Feb 1, 2015

You have mixed something up with your variables, you can subtract timedelta d from datetime.datetime.now() with no issue:

import datetime 
tod = datetime.datetime.now()
d = datetime.timedelta(days = 50)
a = tod - d
print(a)
2014-12-13 22:45:01.743172