Home > Back-end >  AttributeError: attribute 'month' of 'datetime.date' objects is not writable
AttributeError: attribute 'month' of 'datetime.date' objects is not writable

Time:07-21

I just wanted to convert the month format into string. the default format is 2022-07-20 , I want the 7 to output as "July". It's my own code and please correct and suggest me to put the right code. Thank you in advance.

def get_currentDate():
today = date.today()
if today.month == 7:
    today.month = "July"
    print("It's {} {}, {} sir".format(today.month, today.day, today.year))

CodePudding user response:

You cannot change the day, month, and year values of today, so you can make it a list (which you can change the values of)

def get_currentDate():
    today = date.today()
    today = [today.year, today.month, today.day]
    if today[1] == 7:
        today[1] = "July"
        print("It's {} {}, {} sir".format(today[1], today[2], today[0]))

CodePudding user response:

I've come up with this code and it seems I get the output I want and I added also some text in my output.

def get_currentDate():
    this_day = date.today()
    day = int(this_day.strftime("%d"))

    if day == 1 or day == 21 or day == 31:
       print(this_day.strftime("It's %A, {}st of %b %Y ").format(day))
    elif day == 2 or day == 22:
       print(this_day.strftime("It's %A, {}nd of %b %Y ").format(day))
    elif day == 3 or day == 23:
       print(this_day.strftime("It's %A, {}rd of %b %Y ").format(day))
    elif day > 3:
       print(this_day.strftime("It's %A, {}th of %b %Y ").format(day))

Please correct me if I'm wrong , or any suggestion about this. Thank you

  • Related