Show days of the week

Asked

Viewed 143 times

0

I built this code to show the day of the week. It works, but I wonder if there is another way with fewer lines/commands I could use. Or a more 'clean' way so to speak.

import datetime

# Pega a data atual
dia = datetime.date.today().day
ano = datetime.date.today().year
mês = datetime.date.today().month
sem = ("Segunda", "Terça", "Quarta", "Quinta", "Sexta", "Sábado", "Domingo")
ds = ("Segunda", "Terça", "Quarta", "Quinta", "Sexta")

# Verifica que dia é hoje de acordo com o padrão de data em inglês ex:(2021/05/10)
num = datetime.date(ano, mês, dia).weekday()
p = (sem[num])

# De acordo com o número que 'p' tiver, é setado um dia da semana conforme o correspondente na lista 'ds'
# 'ds' é abreviação de Dias da Semana

# Verifica se o dia atual é dia útil, se não for é considerado 'fim de semana'
if p in ds:
    h = 'dia de semana'
else:
    h = 'fim de semana'

# Termina o código mostrando que dia é hoje
if h == 'dia de semana':
    print(f"Tenha uma boa {sem[num]} =D")
else:
    print(f"Tenha um bom {sem[num]} =D")

4 answers

4

There’s a lot of unused code in your algorithm. From what I understand you want to print in "Have a good XXX-Friday" or "Have a good Saturday/Sunday" but you create and not use variables or create unnecessarily.

An example of how it could be done more concisely:

from datetime import date

dia_semana = date.today().weekday()
nomes = ("Segunda", "Terça", "Quarta", "Quinta", "Sexta", "Sábado", "Domingo")

if dia_semana in {5, 6}:
    print(f"Tenha um bom {nomes[dia_semana]} =D")
else:
    print(f"Tenha uma boa {nomes[dia_semana]} =D")

As you will not use the object "today" created with date.today(), I’m not saving anywhere because I just need the day of the week. Then just check if it’s the weekend and print the correct name.

  • I’m still beginner in programming, so this mess in my code kk but its resolution taught me mt, thanks msm

4


First of all, there’s no use datetime.date(ano, mês, dia) if you’re already using today()

And to check if it is Saturday or Sunday just check if the value of weekday is greater than 4, if it is less than 5 is weekday, don’t need of num in (5, 6) (tuple) nor num in {5, 6} (set), just do num < 5, since as I said, the "finals" are 5 and 6, so you know that the "weekdays" are 0 to 4:

Valor Weekday
0 Second
1 Tuesday
2 Fourth
3 Fifth
4 Sixth
5 Saturday
6 Domingo

Using the very library you are already using in your code:

from datetime import date

num = date.today().weekday()

sem = ("Segunda", "Terça", "Quarta", "Quinta", "Sexta", "Sábado", "Domingo")

if num < 5:
    print(f"Tenha uma boa {sem[num]}-feira =D")
else:
    print(f"Tenha um bom {sem[num]} =D")
  • 1

    Boy, how I messed up such a simple thing to do kkkkk I appreciate the help bro<3

3

Yes, it can be simpler.

See that you create 3 times today’s date (date.today() is called 3 times), but only need to call once.

And then you take the day, month and year of today’s date and create another date with these values. Why? date.today() already returns a date with exactly these values, so it is completely unnecessary to create another date with the same day, month and year.

And to format the date, just use strftime, using the format "%A" which corresponds to the day of the week (see more about the formats in documentation). And for it to be in Portuguese, you need to set the locale:

import locale
# setar locale para português
locale.setlocale(locale.LC_ALL, 'pt_BR.utf8')

from datetime import date

hoje = date.today() # data de hoje
if hoje.weekday() in (5, 6): # se o dia da semana é sábado ou domingo
    msg = 'um bom'
else:
    msg = 'uma boa'

print(f'Tenha {msg} {hoje.strftime("%A").title()} =D')

Like weekday() returns a number between 0 and 6 (being Monday=0, Tuesday=1, ..., Saturday=5, Sunday=6), just use this value to check whether it is weekend or not. Then you arrow the message accordingly, and use strftime to get the name of the day of the week. I also used title() because the day of the week was being returned with lowercase letter.

And I also created another variable for the part that varies ("a good"/"a good"), then I only print the message once (as it seems to be always the same message, changing only these details, I found it better so).


Remember that for the above code to work, the locale pt_BR shall be installed in the system as explained here (this link also explains how to check this).

But should the locale nay is installed (and you don’t want/don’t know how to install), then the way is to have the same name list:

from datetime import date

nomes = ["Segunda", "Terça", "Quarta", "Quinta", "Sexta", "Sábado", "Domingo"]
ds = date.today().weekday()
if ds in (5, 6): # se o dia da semana é sábado ou domingo
    msg = 'um bom'
else:
    msg = 'uma boa'

print(f'Tenha {msg} {nomes[ds]} =D')
  • In the end my answer is no longer necessary, his explains more and we end up with an almost equal code. hahahaha

  • @fernandosavio I only answered to talk about strftime, that yours didn’t have. But I guess you don’t need to erase yours no, because you answered before...

  • By incredible q seems, with the use of the locale, you just help me in another code that gave error 'non-utf8' KKKKKK and still breaking helped me with this code, I do not know how thank you <33333

0

As they answered, you can use the weekday to search the tuple, being 0 Monday and 6 Sunday.

    from datetime import date
    diadasemana = ('Segunda', 'terça', 'quarta', 'quinta', 'sexta', 'Sábado', 
    'Domingo')
    print("fim de semana" if (diadasemana[date.today().weekday()]) in (5, 6) else "dia 
    de semana")
    print(f'Tenha uma boa {diadasemana[date.today().weekday()]} :)!')
  • I liked how he used the if and Else in the same line, it was very clean to see kkk vlw the help mano =D

  • @Nerean The problem is he’s checking to see if diadasemana[date.today().weekday()] is 5 or 6 (i.e., if the text is 5 or 6, and never will be, because the texts are "Monday", "Tuesday", etc). It is right to see if the value of weekday is 5 or 6: if date.today().weekday() in (5, 6). And there’d be no need to call date.today().weekday() twice, this is a case where it would be worth saving the value in a variable (not worth "save a line", and for that you had to create the same object twice)

  • Oops, I tested it yesterday and today. That’s correct :) I’m not looking for the text, qdo coloco date.Oday(). weekday inside the key, I’m going to the tuple diadasemana and taking her index to validate my "if". Abs

  • @Cristianomenezessilva I suggest you test on Saturday or Sunday then, and then you will understand what I said: you check if diadasemana[date.today().weekday()] is 5 or 6 (make print(diadasemana[date.today().weekday()]) and see that it prints the text, not the content, then the if is seeing if the text is 5 or 6, so will fail on the weekend). In fact do not even need to wait for the weekend, just change date.today() for date(2021, 5, 15) (Saturday) and see what happens (will say that it is the weekday, and not the weekend).

  • Another detail is that the text "a good one" has been adjusted to "a good one" when it is Saturday or Sunday (that is, it will be "Have ato boto Domingo")

  • Show!! Thank you so much for the answer! : ) abs

Show 1 more comment

Browser other questions tagged

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