简体   繁体   English

Python不会导入函数

[英]Python won't import function

I have a simple time.py file: 我有一个简单的time.py文件:

import datetime
import time
import re
def cnvrt1(time):
    hr = int(re.split(":",time)[0])
    min = int(re.split(":",time)[1])
    sec = int(re.split(" ",re.split(':',time)[2])[0])
    ampm = re.split(" ",re.split(':',time)[2])[1][0]
    zone = re.split(" ",re.split(':',time)[2])[2][0]
    if ampm == 'P' && hr < 12 :
        hr = hr + 12
    elif ampm == 'A' && hr == 12 :
        hr = hr - 12;
    dt = datetime.datetime.strptime(year=2013,month=10,day=22,hour=hr,minute=min,second=sec)
    res1 = time.mktime(dt.timetuple())
    if zone =='M':
        res1 = res1 -  3600000;
    if zone =='C' :
            res1 = res1 - 3600000*2;
    if zone == 'E' :
           res1 = res1 - 3600000*3;
    return res1

However when I say from time import cnvrt1 , it says ImportError: can't import name 'cnvrt1' . 但是当我from time import cnvrt1 ,它说ImportError: can't import name 'cnvrt1' Can anyone point me to what I might be doing wrong? 谁能指出我可能做错了什么?

You are using the wrong name. 您使用的是错误的名称。 There is already a module named time in the standard library, and that module is probably already imported by other code you are using. 标准库中已有一个名为time的模块,该模块可能已由您正在使用的其他代码导入。 You are even using import time in the code you posted here, which would otherwise create a circular import. 您甚至在此处发布的代码中使用import time ,否则将创建循环导入。

The best option is to rename this module to something else. 最好的选择是将此模块重命名为其他内容。

If you are using Python 3, and placed time.py inside a package, you can qualify the import to be within the current package: 如果您使用的是Python 3,并将time.py放在包中,则可以将导入限定在当前包中:

from .time import cnvrt1

Note the . 请注意. . This would allow you to retain the current name; 这将允许您保留当前名称; Python 3 switched to using absolute imports by default and a time module inside a package won't conflict with the global time module. 默认情况下,Python 3切换到使用绝对导入,并且包内的time模块不会与全局time模块冲突。

You are also using invalid Python syntax in your module. 您还在模块中使用了无效的Python语法。 Python uses and , not && for boolean logic: Python使用and ,而不是&&用于布尔逻辑:

if ampm == 'P' && hr < 12 :

should be 应该

if ampm == 'P' and hr < 12:

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

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