program tip

파이썬 시간 비교

radiobox 2020. 9. 24. 07:43
반응형

파이썬 시간 비교


파이썬에서 시간을 어떻게 비교합니까?

날짜 비교를 수행 할 수 있고 "timedelta"도 있지만 현재 시간 (datetime.now ()에서)이 지정된 시간보다 빠르거나 같은지, 늦는 지 확인하는 방법을 찾는 데 어려움을 겪고 있습니다. (예 : 8am) 날짜에 관계없이.


당신은 할 수 없습니다 (오전 8시 매일 발생) 이벤트를 반복, 고정되지 않은에 대해 (예 : "지금"으로) 특정 시점을 비교합니다.

지금이 오늘 오전 8시 이전인지 이후인지 확인할 수 있습니다 .

>>> import datetime
>>> now = datetime.datetime.now()
>>> today8am = now.replace(hour=8, minute=0, second=0, microsecond=0)
>>> now < today8am
True
>>> now == today8am
False
>>> now > today8am
False

당신이 사용할 수있는 time()방법 datetime은 계정에 날짜를 복용하지 않고 비교를 위해 사용할 수있는 하루의 시간을 얻기 위해 개체를 :

>>> this_morning = datetime.datetime(2009, 12, 2, 9, 30)
>>> last_night = datetime.datetime(2009, 12, 1, 20, 0)
>>> this_morning.time() < last_night.time()
True

datetime.datetime 객체를 직접 비교할 수 있습니다.

예 :

>>> a
datetime.datetime(2009, 12, 2, 10, 24, 34, 198130)
>>> b
datetime.datetime(2009, 12, 2, 10, 24, 36, 910128)
>>> a < b
True
>>> a > b
False
>>> a == a
True
>>> b == b
True
>>> 

Roger Pate의 영감 :

import datetime
def todayAt (hr, min=0, sec=0, micros=0):
   now = datetime.datetime.now()
   return now.replace(hour=hr, minute=min, second=sec, microsecond=micros)    

# Usage demo1:
print todayAt (17), todayAt (17, 15)

# Usage demo2:    
timeNow = datetime.datetime.now()
if timeNow < todayAt (13):
   print "Too Early"

datetime에는 비교 기능이 있습니다.

>>> import datetime
>>> import time
>>> a =  datetime.datetime.now()
>>> time.sleep(2.0)
>>> b =  datetime.datetime.now()
>>> print a < b
True
>>> print a == b
False

Another way to do this without adding dependencies or using datetime is to simply do some math on the attributes of the time object. It has hours, minutes, seconds, milliseconds, and a timezone. For very simple comparisons, hours and minutes should be sufficient.

d = datetime.utcnow()
t = d.time()
print t.hour,t.minute,t.second

I don't recommend doing this unless you have an incredibly simple use-case. For anything requiring timezone awareness or awareness of dates, you should be using datetime.

참고URL : https://stackoverflow.com/questions/1831410/python-time-comparison

반응형