0

I am trying to print the current time at a specific time, how come it is not printing what I want it to do? it is just exiting at code 0 when it get to the specific time(12:09)

from datetime import datetime as dt

now = dt.now()

current_time = now.strftime("%H:%M")

for i in range(500000000):
    if current_time == "12:09":
        print("The time is" + current_time)
Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
  • 3
    You assigned *one* value to `current_time`, at the start of your code. The variable is going to retain that value until you explicitly change it; if it wasn't equal to `"12:09"` to start with, it will never be equal to it later. – jasonharper May 28 '22 at 02:15
  • I don't know what your exact use case for this is, but if this is just an example of a code that does _something_ at a specific time, check related [Start a Function at Given Time](https://stackoverflow.com/q/11523918/2745495). – Gino Mempin May 28 '22 at 02:23
  • In your own words, why should `current_time` ever be equal to `"12:09"`? Also, please read the [formatting help](https://stackoverflow.com/help/formatting) and make sure you understand how to post multi-line code with proper formatting. – Karl Knechtel May 28 '22 at 02:26
  • cast your `current_time` to string- str(current_time) == "12:09", your current_time type is datetime and you have to cast to string then equal to specific time – Ashkan Goleh Pour May 28 '22 at 05:03

1 Answers1

1

You're only getting the time once. After you do current_time = now.strftime("%H:%M"), the current_time variable isn't going to change. If you want that, you need to move that code inside the loop so that they get run repeatedly:

for i in range(500000000):
    now = dt.now()                                # move these lines
    current_time = now.strftime("%H:%M")          # inside the loop

    if current_time == "12:09":
        print("The time is" + current_time)

Note that this code is going to thrash your CPU pretty hard, since the loop doesn't take any significant amount of time, and will likely see the same time string thousands or more times in a row. You may want to call time.sleep or a similar function to delay 30+ seconds between checks of the time (since you only care about the minutes).

Blckknght
  • 100,903
  • 11
  • 120
  • 169