0

I'm trying to compare two time in python:

from datetime import time, datetime

start = datetime(2020, 1 , 18, 9,30)
current_time = datetime.now()

if (current_time == start):
    print("Time Matched")

Now when i'm running the code and when time reaches above mentioned start time, it does not prints "Time is matched" Kindly help me out in what im trying to do with this code is that when start time matches my laptop time i'm trying to execute some code , buy i'm not able to do so.

petezurich
  • 9,280
  • 9
  • 43
  • 57
tanjiro
  • 13
  • 4
  • 1
    `now()` may have seconds and milliseconds which can make difference. – furas Jan 18 '20 at 05:35
  • 3
    Does this answer your question? [Python time comparison](https://stackoverflow.com/questions/1831410/python-time-comparison) – Rahul Bharadwaj Jan 18 '20 at 05:36
  • if you want to compare date in python, I suggest you to use date object instead datetime because datetime takes account hours, minutes, seconds, milliseconds, ... It will be difficult to get same date in this case – m0r7y Jan 18 '20 at 05:39

1 Answers1

0

**Your PC Note down time with millisecond that's why you are not able to get desired result **

If You Provide second in datetime obj then -\

from datetime import time, datetime

start = datetime(2020, 1 , 18, 9,30)
current_time = datetime.now()
start_str=str(start)
current_str=str(surrent_time)
if(start_str==current_str):
      print(match)

**General Method **

if we want to match particular part This is 23 hour format if you want 12 hour format you can find diff parameter answer

 start = datetime(2020, 1 , 18, 9,30)
 current = datetime.now()
 start_year=start.strftime("%Y")
 start_month=start.strftime("%m")
 start_day=start.strftime("%H")
 start_hours=start.strftime("%H")
 start_min=start.strftime("%M")
 print(start_year,start_month,start_day,start_hours,start_min)


 current_year=current.strftime("%Y")
 current_month=current.strftime("%m")
 current_day=current.strftime("%H")
 current_hours=current.strftime("%H")
 current_min=current.strftime("%M")
 print(current_year,current_month,current_day,current_hours,current_min)

if((start_year==current_year) and (start_month==current_month)  and (start_day==current_day) and (start_hours==current_hours) and (start_min==current_min)):
      print("match")
Welcome_back
  • 1,245
  • 12
  • 18