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
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.
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.
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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With