create random number in python beginning with the year

0

Hello, I'm trying to create a variable to return a protocol number by picking up the current year, then 4 houses from the beginning, from the smallest to the largest, for example. 20180001, 20180002 etc.

To catch only the year I used

def numero_solicitacao():
    now = datetime.datetime.now()
    return now.year

The question is how to join the variable with the value of the year plus the growing houses in the front?

    
asked by anonymous 26.09.2018 / 18:54

2 answers

1

To solve the problem of "concatenating" the numbers just use math, if you are using the year with 4 digits as a base, simply multiply the year by 10,000, ie you will add 4 zeros to the right of the year. After that, just add the next number.

2018 * 10000 + 1 # 20180001
2018 * 10000 + 2 # 20180002
2018 * 10000 + 3 # 20180003
# ...

Example of a generator that does what you need:

def numero_solicitacao(ano = None, numero_inicial = 1):
    ano_atual = ano or date.today().year
    numero = numero_inicial

    while numero <= 9999:
        yield ano_atual * 10000 + numero
        numero += 1

gen_numero = numero_solicitacao()
print(next(gen_numero))  # 20180001
print(next(gen_numero))  # 20180002
print(next(gen_numero))  # 20180003

gen_numero = numero_solicitacao(2011, 500)
print(next(gen_numero))  # 20110500
print(next(gen_numero))  # 20110501
print(next(gen_numero))  # 20110502

Note that I set the parameters ano and numero_inicial so that you can start at the number you need, this way you can get the last record that you have in the database and use the generator to follow it number onwards.

Repl.it with the code working.

    
26.09.2018 / 19:26
0

based on your answer Fernando I overwritten the save method of the model to get the YEAR plus two house 00 plus the ID

def save(self, *args, **kwargs):
    super (Solicitacao, self).save(*args, **kwargs)
    ano_corrente = datetime.datetime.now()
    if not self.numero_descricao:
        self.numero_descricao = f"{ano_corrente.year}00{self.id}"
        self.save

Thank you very much for the help of all!

    
26.09.2018 / 19:52