Home > Net >  Creating a date using another date in python using datetime module
Creating a date using another date in python using datetime module

Time:02-03

I am making a simple program to calculate the difference between two dates: A specified date and the current date using datetime module.

def difference(current, until):
    year, month, day = current.year, until.month, until.date
    print("Year:", current.year, "Type:", type(current.year))
    this_year = datetime.datetime(year, month, day)
    return this_year - current

I can see that type(current.year) is an 'int'. However, when I try to make a new date, an error occurs. Output:

Year: 2023 Type: <class 'int'>
    this_year = datetime.datetime(year, month, day)
TypeError: an integer is required (got type builtin_function_or_method)

CodePudding user response:

tl;dr

Change

year, month, day = current.year, until.month, until.date

to

year, month, day = current.year, until.month, until.day

The current.year is definitely an integer. The issue is with your until.date variable that is getting assigned to day.

As mentioned in @chepner's comment: until.date is a bound method that returns a datetime.date object. Read more in the documentation about it here - https://docs.python.org/3/library/datetime.html#date-objects

Meanwhile, changing your until.date to until.day will fix your issue.

  • Related