Home > Net >  Python datetime if week day ... do
Python datetime if week day ... do

Time:12-01

I will make a python script that say me the correct weekday. This is what i imagine:

def wishMe():

hour = datetime.datetime.now().hour
if hour >= 0 and hour < 12:
    os.system("say Good Morning")
elif hour >= 12 and hour < 18:
    os.system("say Good Afternoon")
else:
    os.system("say Good Evening")

wishMe()

But with weekdays.

if day >= Monday:
    os.system("say It's Monday")
if day >= Tuesday:
    os.system("say It's Tuesday")

.....

I now there's a simpler way. Like this:

  day = datetime.datetime.now().strftime('%A')
  print(day)

But later i will change it a little bit.

I hope anybody can help me. (and understand what i mean!)

CodePudding user response:

You could use string manipulation to combine the output of strftime with the code-segment above. For instance, f-strings to combine the say "It's Tuesday" and output of strftime.

For example: os.system(f"say It is {day}"). Note the f in front of the string denoting that it is a f-string. The curly braces are used to insert values from your program into the string.

You can find more information about f-strings here: https://docs.python.org/3/tutorial/inputoutput.html

Note that the command you are passing to os.system is not compatible across different operating systems. The utility "say" exists in Mac OS, but not Windows and Linux. Also special characters like ' can cause trouble when executed in the shell by os.system.

In addition to strftime there are two functions in the datetime-library called weekday and isoweekday. From the docs:

datetime.weekday()

Return the day of the week as an integer, where Monday is 0 and Sunday is 6. The same as self.date().weekday(). See also isoweekdatetimeday().

datetime.isoweekday()

Return the day of the week as an integer, where Mondatetimeday is 1 and Sunday is 7. The same as self.date().isoweekday(). See also weekday(),

Ref: https://docs.python.org/3/library/datetime.html#datetime.weekday

You could use these to switch based on numbers, or simply do your if/else statements by string-comparison.

CodePudding user response:

("Monday","Tuesday","Wednesday","Thursday","Friday","Saturday")[datetime.datetime.now().weekday()]

datetime.datetime.now() will give the date and .weekday() will give the weekday from 0 to 6, then use that as an index for a tuple with the days

  • Related