简体   繁体   中英

How to create a function to calculate days of years?

I want to create function to calculate the days of year as code below. While the python throw out typeError: 'int'object is not callable. How to solve this problem? Thanks!

def DaysOfYear(year, month, day):

import datetime

dt=datetime.datetime(year,month, day, 0, 0)
tt=dt.timetuple().tm_yday()

DaysOfYear(2012, 11, 7)

The below code with specific days works. But I need to call function with variable (year, month,day) What should I do to revise the above code?

from datetime import date dt=date(2012,11,7) print(dt.timetuple().tm_yday)

Replace

tt=dt.timetuple().tm_yday()

by

dt.timetuple().tm_yday

tm_yday is an attribute (with value int , being non-callable since its not a function) in datetime.timetuple() of type time.struct_time .

>>> dt=datetime.datetime(2019, 12, 24, 0, 0)
>>> dt.timetuple()
time.struct_time(tm_year=2019, tm_mon=12, tm_mday=24, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=1, tm_yday=358, tm_isdst=-1)

The following implements what the others stated and works:

def DaysOfYear(year, month, day):
    import datetime
    dt=datetime.datetime(year,month, day, 0, 0)
    tt=dt.timetuple().tm_yday
    return tt

print( DaysOfYear(2011,11,1) )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM