简体   繁体   English

如何创建一个函数来计算年的天数?

[英]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.虽然 python 抛出 typeError: 'int'object is not callable。 How to solve this problem?如何解决这个问题呢? Thanks!谢谢!

def DaysOfYear(year, month, day): def DaysOfYear(年、月、日):

import datetime

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

DaysOfYear(2012, 11, 7) 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)从日期时间导入日期 dt=date(2012,11,7) 打印(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 . tm_ydaytime.struct_time类型的datetime.timetuple()的一个属性(值为int ,由于它不是函数,因此不可调用datetime.timetuple()

>>> 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) )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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