[Python] Why does this Python variable assignment fail?

Discussão em 'Python' iniciado por Stack, Março 22, 2025.

  1. Stack

    Stack Membro Participativo

    This works:

    from datetime import date
    currentYear = date.today().strftime("%Y")
    date = date.today().strftime("%e/%-m/%y")
    print(date)
    print(currentYear)


    But it doesn't work if I reverse the order of the variable assignments:

    from datetime import date
    date = date.today().strftime("%e/%-m/%y")
    currentYear = date.today().strftime("%Y")
    print(date)
    print(currentYear)


    It returns:

    Traceback (most recent call last):
    File "/home/emma/x", line 5, in <module>
    currentYear = date.today().strftime("%Y")
    ^^^^^^^^^^
    AttributeError: 'str' object has no attribute 'today'

    Continue reading...

Compartilhe esta Página