create random number in python starting with the year

Asked

Viewed 102 times

0

hello I am trying to create a variable to return me a protocol number catching the current year after 4 front houses starting from the smallest to the largest, example. 20180001, 20180002 etc.

to catch only the year used

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

doubt is like joining variable with year value plus growing houses in front?

  • Hello Gustavo, want to return a variable of type 2018+ (4 dígitos aleatórios)?

  • this friend however not adding up the values already tried to create the variable picking the year and another the random number but either returned the sum of the two or a tuple.

2 answers

1


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

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

Example of a Generator who 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 that is required, that way you can take the last record that you have in the database and use Generator to follow from that number on.

Repl.it with the code working.

0

based on his reply Fernando I overwrote the model save method to catch 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

It worked out thank you so much for all your help!!!

Browser other questions tagged

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