While Python repetition structure

Asked

Viewed 401 times

0

Good afternoon guys, I’m trying to make a program that always updates a month to my date: Example I have a minimum date, maximum date and the current date I want that whenever my min date is less than the maximum one more month to arrive at the current date , Then when I get to the current date stop the loop I made the following code. Thank you

from datetime import datetime, timedelta

# Declaração de variaveis
meses = 1
dias_por_mes = 31
data_min = datetime.strptime('2012-10-01', '%Y-%m-%d')   
data_max = datetime.strptime('2019-04-10', '%Y-%m-%d')
hoje = datetime.now()

# Estrutura de repetição
while (data_min < data_max):
    print(data_min)
    data_futura = data_min + timedelta(dias_por_mes*meses)
    print(data_futura)
    if data_min == data_max:
        break
        print('Todos os registros foram inseridos!!!')
  • 3

    Good afternoon Nidorus! Please be more specific where this your problem or doubt.

1 answer

2


You’re not incrementing any variable, just endlessly assigning data_futura with data_min + timedelta(dias_por_mes*meses). Do so:

data_min = data_min + timedelta(dias_por_mes*meses)

It is worth noting that not every month has 31 days, with the top line the code only for 2019-04-15. If you want, in fact, to always add a month to data_min a more correct approach would be through the library dateutil (pip install python-dateutil), for example:

from dateutil.relativedelta import relativedelta
...
data_min = data_min + relativedelta(months = 1)

But still, the code won’t stop at data_max, unless the days of both dates are identical. In your case (I didn’t stop to think about them all), the following logic will work:

from datetime import datetime, timedelta
from dateutil.relativedelta import relativedelta

# Declaração de variaveis
data_min = datetime.strptime('2012-10-01', '%Y-%m-%d')
data_max = datetime.strptime('2019-04-10', '%Y-%m-%d')
dias = data_max.day - data_min.day
data_max_menos_um_mes = data_max - relativedelta(months = 1)
hoje = datetime.now()

# Estrutura de repetição
while (data_min < data_max):
    data_min = data_min + relativedelta(months = 1)
    if data_min.year == data_max.year and data_min.month == data_max_menos_um_mes.month:
        data_min = data_min + relativedelta(months = 1, days = dias)
        print('Todos os registros foram inseridos!!!')
        break
  • Thank you very much, the explanation helped me a lot

Browser other questions tagged

You are not signed in. Login or sign up in order to post.