Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python won't import function

I have a simple time.py file:

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'. Can anyone point me to what I might be doing wrong?

like image 309
Rohit Pandey Avatar asked Feb 28 '26 09:02

Rohit Pandey


1 Answers

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. You are even using import time in the code you posted here, which would otherwise create a circular import.

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:

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.

You are also using invalid Python syntax in your module. Python uses and, not && for boolean logic:

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

should be

if ampm == 'P' and hr < 12:
like image 83
Martijn Pieters Avatar answered Mar 01 '26 22:03

Martijn Pieters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!