0
Friends,
I have the following code in Python:
data_hoje = time.strftime("%d %b %Y", time.gmtime() ) #data de hoje
data_desejada = time.strftime("%d %b %Y", time.gmtime(time.time() + (3600 * 24 * 2))) # daqui a 2 dias
I know that in Python we don’t have the switch/case structure that is used in other languages. The above code is very repetitive. How to make it more "lean", ie avoid the use of various if/Elif?
if data_hoje[0:2] == "01":
data_nova = data_hoje[1:2] + data_hoje[2::]
elif data_hoje[0:2] == "02":
data_nova = data_hoje[1:2] + data_hoje[2::]
elif data_hoje[0:2] == "03":
data_nova = data_hoje[1:2] + data_hoje[2::]
elif data_hoje[0:2] == "04":
data_nova = data_hoje[1:2] + data_hoje[2::]
elif data_hoje[0:2] == "05":
data_nova = data_hoje[1:2] + data_hoje[2::]
elif data_hoje[0:2] == "06":
data_nova = data_hoje[1:2] + data_hoje[2::]
elif data_hoje[0:2] == "07":
data_nova = data_hoje[1:2] + data_hoje[2::]
elif data_hoje[0:2] == "08":
data_nova = data_hoje[1:2] + data_hoje[2::]
elif data_hoje[0:2] == "08":
data_nova = data_hoje[1:2] + data_hoje[2::]
else:
data_nova = data_hoje
if data_desejada[0:2] == "01":
data_nova2 = data_desejada[1:2] + data_desejada[2::]
elif data_desejada[0:2] == "02":
data_nova2 = data_desejada[1:2] + data_desejada[2::]
elif data_desejada[0:2] == "03":
data_nova2 = data_desejada[1:2] + data_desejada[2::]
elif data_desejada[0:2] == "04":
data_nova2 = data_desejada[1:2] + data_desejada[2::]
elif data_desejada[0:2] == "05":
data_nova2 = data_desejada[1:2] + data_desejada[2::]
elif data_desejada[0:2] == "06":
data_nova2 = data_desejada[1:2] + data_desejada[2::]
elif data_desejada[0:2] == "07":
data_nova2 = data_desejada[1:2] + data_desejada[2::]
elif data_desejada[0:2] == "08":
data_nova2 = data_desejada[1:2] + data_desejada[2::]
elif data_desejada[0:2] == "08":
data_nova2 = data_desejada[1:2] + data_desejada[2::]
else:
data_nova2 = data_desejada
Wow - this code is absurdly repetitive -now, I don’t see how "switch Casse" would reduce the number of its lines - the answers reflect smarter ways to do this without if/Elif or switch/case. Now - to do operations with dates, you should use the Python dattime module, and not do operations with text, which can break dozens of different ways.
– jsbueno