user3702643
user3702643

Reputation: 1505

checking if two datetime objects are the same

import datetime

time = datetime.time(21) 

while True:
    print(datetime.datetime.now())
    if datetime.datetime.now() == time:
        break

I am trying to set a specific time to run a function in my program. Unfortunately, the loop did not exit at 2100hrs as expected. Why is this so?

Upvotes: 0

Views: 1009

Answers (3)

DirtyBit
DirtyBit

Reputation: 16782

import datetime      

# set the datetime you want the loop to break out 
# datetime.datetime(year, month, date, hour, seconds)

set_dt = datetime.datetime(2019, 2, 8, 18, 19) 

while True:
   print("set date time:", set_dt)
   print(datetime.datetime.now())

   # check if the current date time is greater than the set_dt
   if datetime.datetime.now() > set_dt:
      break
print("out of loop")

OUTPUT:

.
. 
.
set date time: 2019-02-08 18:19:00
2019-02-08 18:18:59.999428
set date time: 2019-02-08 18:19:00
2019-02-08 18:18:59.999428
set date time: 2019-02-08 18:19:00
2019-02-08 18:18:59.999428
out of loop

EDIT:

If you only want the loop to break out when a certain hour:

if datetime.datetime.now().hour == set_dt.hour:
    break

Upvotes: 0

John Keyes
John Keyes

Reputation: 5604

It sounds like you just want to compare the hour:

import datetime

time = datetime.time(21)
print(time)

while True:
    print(datetime.datetime.now())
    if datetime.datetime.now().hour == time.hour:
        break

That's if you really need to write this rather than using a built-in system scheduler like cron.

Upvotes: 3

Maheshwar Kuchana
Maheshwar Kuchana

Reputation: 92

If you want to just compare dates,

yourdatetime.date() < datetime.today().date()

Or, obviously,

yourdatetime.date() == datetime.today().date()

If you want to check that they're the same date.

The documentation is usually helpful. It is also usually the first google result for python thing_i_have_a_question_about. Unless your question is about a function/module named "snake".

Basically, the datetime module has three types for storing a point in time:

  • date for year, month, day of month

  • time for hours, minutes, seconds, microseconds, time zone info

  • datetime combines date and time. It has the methods date() and time() to get the corresponding date and time objects, and there's a handy combine function to combine date and time into a datetime.

Upvotes: -1

Related Questions