4

I tried reading through some of the other questions but I still can't get it to work.

Basically I'm using a quick and dirty function called time_string() to return the date and time in a string formatted the way I want. If I run time_string directly, it works fine. If I call it from another function I get an AttributeError.

time_string

import time
def time_string(): #Never mind the unreadable formatting
    return str(time.localtime().tm_hour)+':'+str(time.localtime().tm_min)+':'+str(time.localtime().tm_sec)+\
           ' '+str(time.localtime().tm_year)+'/'+str(time.localtime().tm_mon)+'/'+str(time.localtime().tm_mday)

if __name__ == '__main__':
    print time_string()

Running time_string directly

13:46:13 2012/7/19

Other function

from misc.time_string import time_string
def main():
    print time_string()

if __name__ == '__main__':
    main()

Running other function

Traceback (most recent call last): File "#Filepath#", line 10, in main() File "#Filepath#", line 7, in main print time_string() File "#Filepath#", line 9, in time_string ' '+str(time.localtime().tm_year)+'/'+str(time.localtime().tm_mon)+'/'+str(time.localtime().tm_mday) AttributeError: 'module' object has no attribute 'localtime'

I'm assuming its some issue with time not getting imported or something but it's boggling my mind

Thanks for the help!

9
  • 2
    Did you named one of your modules time.py b/c i think it's shadowing the stdlib time module. Commented Jul 19, 2012 at 19:52
  • 1
    I've tried renaming the module and function name to various things, including not using the same name, but to no avail Commented Jul 19, 2012 at 19:53
  • 5
    Y U NO strftime? Commented Jul 19, 2012 at 19:54
  • I copied and pasted these two scripts, and they worked fine in a vacuum. the only change I made was "from misc.time_string..." became "from misc import time_string" Commented Jul 19, 2012 at 19:56
  • 2
    in your time_string.py and after import time put this line: print repr(test) and tell us what you see, if you are really importing the stdlib time you should get: <module 'time' (built-in)> if not you will get something lile: <module 'time' from '<some_path>'> Commented Jul 19, 2012 at 19:56

1 Answer 1

16

The problem is that you have or at one time had a time.py file in the directory where you run the script, causing the wrong time module to be imported.

Even if you remove the time.py file, there still is a compiled time.pyc file that gets imported.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.