Python - defining global name datetime
Question: I'm trying to create a function where I use various functions from the
datetime module, such as strftime, strptime and timedelta.

I feel like I've tried everything, but every time I am told this:

    
    
          4 date = '2012.09.07'
          5 
    ----> 6 q = net(date)
          7 print q
    
    /Users/fb/Documents/Python_files/test_function.pyc in net(date)
          1 def net(date):
    ----> 2     b = datetime.strptime(a, '%Y.%m.%d')
          3     c = b.strftime('%d:%m:%y')
          4     return c
    
    NameError: global name 'datetime' is not defined
    

I've read that others probably experience the same problem as I, namely ' It
works in the python interpreter but not in the script'. Can anyone help,
please?


Answer: You need to import the `datetime` object _in your module_ :

    
    
    from datetime import datetime
    

at the top of `test_function.py`.

In your interpreter session you probably already imported the object.

Your whole module will then look like:

    
    
    from datetime import datetime
    
    def net(date):
        b = datetime.strptime(date, '%Y.%m.%d')
        c = b.strftime('%d:%m:%y')
        return c
    

where I replaced `a` with `date`, since that is the name of the actual
argument to the function.

Note that the `datetime` _module_ contains a `datetime` _class_ , which is the
only thing imported here. If you need access to the `date` and `timedelta`
classes as well, import these explicitly (`from datetime import datetime,
date, timedelta`) or import _just_ the module and refer to the contents as
attributes (`import datetime`, then `datetime.datetime.strptime()` and
`datetime.date.today()`, etc.).

