Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python current time comparison with other time

I am looking for a comparison of two times in Python. One time is the real time from computer and the other time is stored in a string formatted like "01:23:00".

import time

ctime = time.strptime("%H:%M:%S")   # this always takes system time
time2 = "08:00:00"

if (ctime > time2):
    print("foo")
like image 884
Yatish Prasad Avatar asked Dec 25 '22 01:12

Yatish Prasad


1 Answers

import datetime

now = datetime.datetime.now()

my_time_string = "01:20:33"
my_datetime = datetime.datetime.strptime(my_time_string, "%H:%M:%S")

# I am supposing that the date must be the same as now
my_datetime = now.replace(hour=my_datetime.time().hour, minute=my_datetime.time().minute, second=my_datetime.time().second, microsecond=0)

if (now > my_datetime):
    print("Hello")

EDIT:

The above solution was not taking into account leap second days (23:59:60). Below is an updated version that deals with such cases:

import datetime
import calendar
import time

now = datetime.datetime.now()

my_time_string = "23:59:60" # leap second
my_time_string = now.strftime("%Y-%m-%d") + " " + my_time_string # I am supposing the date must be the same as now

my_time = time.strptime(my_time_string, "%Y-%m-%d %H:%M:%S")

my_datetime = datetime.datetime(1970, 1, 1) + datetime.timedelta(seconds=calendar.timegm(my_time))

if (now > my_datetime):
    print("Foo")
like image 96
felipeptcho Avatar answered Dec 26 '22 14:12

felipeptcho