Why do I have to use a global for imported variable?

Question:

import datetime
from datetime import date

def get_one_week():
    global date
    seven_dates = []
    date = date.today()
    for i in range(7):
        date += datetime.timedelta(days=-1)
        date_str = date.strftime('%Y%m%d')
        seven_dates.append(date_str)
    return seven_dates

print(get_one_week())

This will print out:

['20220901', '20220831', '20220830', '20220829', '20220828', '20220827', '20220826']

My question, both ‘date’ and ‘datetime’ are imported variables, but why do I have use a global declaration for the ‘date’ but not for the ‘datetime’ variable?

Asked By: marlon

||

Answers:

It’s because you declared your variable date so python thinks that you referenced the local variable before any assignment try change it to other name so it will use the global one

import datetime
from datetime import date

def get_one_week():
    seven_dates = []
    d = date.today()
    for i in range(7):
        d += datetime.timedelta(days=-1)
        date_str = d.strftime('%Y%m%d')
        seven_dates.append(date_str)
    return seven_dates
    
print(get_one_week())
Answered By: Yafaa Ben Tili
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.