Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the date n days ago in Python?

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

like image 396
Dirty_Fox Avatar asked Feb 01 '15 22:02

Dirty_Fox


People also ask

How do I subtract 7 days from a date in Python?

You can subtract a day from a python date using the timedelta object. You need to create a timedelta object with the amount of time you want to subtract. Then subtract it from the date.

How do you add or subtract days from a date in Python?

For adding or subtracting Date, we use something called timedelta() function which can be found under the DateTime class. It is used to manipulate Date, and we can perform arithmetic operations on dates like adding or subtracting.

How do you subtract dates in Python?

Use the strptime(date_str, format) function to convert a date string into a datetime object as per the corresponding format . To get the difference between two dates, subtract date2 from date1.


2 Answers

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 
like image 146
Padraic Cunningham Avatar answered Sep 24 '22 00:09

Padraic Cunningham


Below code should work

from datetime import datetime, timedelta  N_DAYS_AGO = 5  today = datetime.now()     n_days_ago = today - timedelta(days=N_DAYS_AGO) print today, n_days_ago 
like image 40
Amaresh Narayanan Avatar answered Sep 20 '22 00:09

Amaresh Narayanan