Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: unsupported type for timedelta days component: datetime.datetime

Tags:

python

I am trying to perform some date arithmetic in a function.

from datetime import datetime, timedelta

def foo(date1, summing_period):
    current_period_start_date = date1 - timedelta(days=summing_period)
    # Line above causes the error:
    # TypeError: unsupported type for timedelta days component: datetime.datetime

First arg is a datetime obj and 2nd arg is an integer

What is causing this error, and how do I fix it?

like image 928
Homunculus Reticulli Avatar asked Jul 24 '12 11:07

Homunculus Reticulli


2 Answers

summing_period should be an integer (representing the number of days), not a datetime object.

>>> timedelta(days=datetime.now())
TypeError: unsupported type for timedelta days component: datetime.datetime

>>> timedelta(days=5)
datetime.timedelta(5)
like image 70
eumiro Avatar answered Sep 20 '22 11:09

eumiro


If you want use arg on function, try something like this:

from datetime import timedelta, datetime

def fromdate(howManyDaysYouWantToBack):
    searchingDate  = datetime.today() - timedelta(days=howManyDaysYouWantToBack)
    timestampSearchingDate = (int(searchingDate.timestamp()))
    return timestampSearchingDate

Argument, on this case is days=float, you need to get this value from some place on your code, for example:

howManyDaysYouWantToBack = float(input("How many days you want to back? "))

You can use "float" or "int", on both cases this function will be works.

like image 27
snabo Avatar answered Sep 18 '22 11:09

snabo