Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Dates and Times in Python (2014) Dates and Times Time Tango

How to fix UnboundLocalError without using global method

Hello,

When I was first doing this task the following code was my first attempt.

I know why I was not passing the challenge and I know what the issue was.

Please do NOT give me answers or tips to solve this task because I already solved it.

What I am more interested in is like the title say how to fix that error without using global method.

If I run this code I will get UnboundLocalError: local variable 'datetime' referenced before assignment.

I looked online and figured out what this error means and one way to fix it by using global method.

But, here is the issue, in order to use the global method, it seems that I can not assign any parameter as I will get a syntax error!

But say that I want to keep d and t as the parameters for the function, how would I get past this unboundlocalerror?

combo.py
import datetime

d = '2015/7/21'
t = '5:30'

def time_tango(d, t):
    accurate_time = d + " " + t
    date_format = '%Y/%m/%d %H:%M'
    datetime = datetime.datetime.strptime(accurate_time, date_format)
    return datetime

print(time_tango(d, t))

1 Answer

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,457 Points

The issue is the code imports datetime then later assigns datetime = which overrides the import in the namespace. So when the code gets to datetime.datetime(), it has no idea what you mean.

:point_right: change the variable name to dtime or some other and you're golden

That is, the unbound error will be fixed. Your code needs fixing to pass the challenge.

You don't need to reconstruct the time manually using strptime, you may use datetime.datetime.combine(d, t)

Hello,

Thank you for your response! I did not think that assigning a variable with the same name as the imported library will cause this issue. I suspected that imported library names were not going to be correlated to the variable.

Now thanks to you I will know!