Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

format date in python datatime

I wanted to format the string last_date to d/m/Y. Without formatting it runs but I need formatting

    from datetime import date
    from datetime import datetime
    from datetime import timedelta
    from calendar import monthrange
    data = date.today()
    data_atual = data.strftime('%d/%m/%Y')
    print(data_atual)


    data_e_hora_atuais = datetime.now()
    fuso_horario = timezone("America/Sao_Paulo")
    data_e_hora_sao_paulo = data_e_hora_atuais.astimezone(fuso_horario)
    data_e_hora = data_e_hora_sao_paulo.strftime("%d/%m/%Y %H:%M")
    print(data_e_hora)

    last_date = data.replace(day=monthrange(data_atual.year, data_atual.month))
    last_date_formated = last_date.strftime('%d/%m/%Y')
    print(last_date)

this output:

Traceback (most recent call last):
  File "C:\Users\Francisco\PycharmProjects\INSS\MODULOS\buscardados.py", line 17, in <module>
    last_date = data.replace(day=monthrange(data_atual.year, data_atual.month))
AttributeError: 'str' object has no attribute 'year'

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The data_atual is string type. So you can’t access any attribute like that.
If you want to access data_atual.year or month

You need to cast string type to datetime object.

Or use data instead. e.g. data.year, data.month

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading