Home > Net >  format date in python datatime
format date in python datatime

Time:06-14

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'

CodePudding user response:

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

  • Related