Python中datetime导入冲突引发AttributeError问题求助
我编写了两个Python函数,分别使用不同的datetime调用方式,已知问题出在导入环节但不知如何解决。以下是我的代码:
from datetime import datetime import datetime def upload_video(title,description,tags,upload_year,uplaod_month,upload_day): upload_date_time = datetime.datetime(upload_year,uplaod_month,upload_day, 8, 00, 0).isoformat() + '.000Z' print(f"this is a upload time {upload_date_time}") request_body = { 'snippet': { 'categoryI': 19, 'title': title, 'description': description, 'tags': tags }, 'status': { 'privacyStatus': 'private', 'publishAt': upload_date_time, 'selfDeclaredMadeForKids': False, }, 'notifySubscribers': False } mediaFile = MediaFileUpload('output.MP4') response_upload = service.videos().insert( part='snippet,status', body=request_body, media_body=mediaFile ).execute() def date_calculator(): days_in_months = {1:31, 2:28, 3:31, 4:30, 5:31, 6:30, 7:31, 8:31, 9:30, 10:31, 11:30, 12:31} year = datetime.now().year month = datetime.now().month # Read the last used date from the text file with open("last_used_date.txt", "r") as f: last_used_date = f.read().strip() # If the file is empty or the date is invalid, set the last used date to the current date if not last_used_date or not all(c.isdigit() for c in last_used_date.split(".")): last_used_day = datetime.now().day last_used_month = month else: last_used_day, last_used_month = map(int, last_used_date.split(".")[:2]) # Generate new dates until the next one is greater than the current date number = 0 number_test = 1 while True: date = "{}.{}.{}".format(last_used_day, last_used_month, year) number += 1 if last_used_day == days_in_months[month]: last_used_month += 1 last_used_day = 1 else: last_used_day += 1 if number == 2: last_used_day += 1 number = 0 number_test += 1 if (last_used_month > month or (last_used_month == month and last_used_day > datetime.now().day)): with open("last_used_date.txt", "w") as f: f.write("{}.{}.{}".format(last_used_day, last_used_month, year)) break return last_used_day,last_used_month,year
当使用上述导入顺序时,报错如下:
Traceback (most recent call last):
File "c:\Users\Lukas\Dokumenty\python_scripts\Billionare livestyle\main.py", line 233, in
day,month,year = date_calculator()
File "c:\Users\Lukas\Dokumenty\python_scripts\Billionare livestyle\main.py", line 162, in date_calculator
year = datetime.now().year
AttributeError: module 'datetime' has no attribute 'now'
当调整导入顺序为import datetime后再from datetime import datetime时,报错如下:
Traceback (most recent call last):
File "c:\Users\Lukas\Dokumenty\python_scripts\Billionare livestyle\main.py", line 235, in
upload_video(title,"#Shorts", ["motivation", "business", "luxury", "entrepreneurship", "success", "lifestyle", "inspiration", "wealth", "financial freedom", "investing", "mindset", "personal development", "self-improvement", "goals", "hustle", "ambition", "rich life", "luxury lifestyle", "luxury brand", "luxury travel", "luxury cars"],year,month,day)
File "c:\Users\Lukas\Dokumenty\python_scripts\Billionare livestyle\main.py", line 74, in upload_video
upload_date_time = datetime.datetime(upload_year,uplaod_month,upload_day, 8, 00, 0).isoformat() + '.000Z'
AttributeError: type object 'datetime.datetime' has no attribute 'datetime'
问题根源
你同时混用了from datetime import datetime和import datetime,这两个语句会互相覆盖datetime这个名称,导致调用逻辑混乱:
- 先导入
datetime类再导入datetime模块:模块会覆盖类,此时datetime指向模块,而now()是datetime类的方法,模块本身没有这个属性,所以报错。 - 先导入模块再导入类:类会覆盖模块,此时
datetime指向datetime.datetime类,再调用datetime.datetime()相当于在类里找datetime属性,自然不存在。
解决办法
选一种统一的导入方式,不要混用:
方案1:只导入datetime模块
保留import datetime,删除from datetime import datetime,然后修改函数内的调用:
date_calculator里的datetime.now()→datetime.datetime.now()upload_video里的datetime.datetime(...)保持不变
修改后的导入和关键调用示例:
import datetime def date_calculator(): # ... year = datetime.datetime.now().year month = datetime.datetime.now().month # ... def upload_video(title,description,tags,upload_year,uplaod_month,upload_day): upload_date_time = datetime.datetime(upload_year,uplaod_month,upload_day, 8, 00, 0).isoformat() + '.000Z' # ...
方案2:只导入datetime类
保留from datetime import datetime,删除import datetime,然后修改函数内的调用:
date_calculator里的datetime.now()保持不变upload_video里的datetime.datetime(...)→datetime(...)
修改后的导入和关键调用示例:
from datetime import datetime def date_calculator(): # ... year = datetime.now().year month = datetime.now().month # ... def upload_video(title,description,tags,upload_year,uplaod_month,upload_day): upload_date_time = datetime(upload_year,uplaod_month,upload_day, 8, 00, 0).isoformat() + '.000Z' # ...
额外提示
代码中upload_video函数存在拼写错误:uplaod_month应该改为upload_month,不修正的话后续运行还会报参数不匹配的错误。
内容的提问来源于stack exchange,提问作者Test000

