파이썬 시간 비교
파이썬에서 시간을 어떻게 비교합니까?
날짜 비교를 수행 할 수 있고 "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
'program tip' 카테고리의 다른 글
null이 포함 된 std :: string을 어떻게 구성합니까? (0) | 2020.09.24 |
---|---|
SQL Server 2005에서 교착 상태 진단 (0) | 2020.09.24 |
한 클래스를 제외한 모든 요소에 대해 CSS 규칙을 만드는 방법은 무엇입니까? (0) | 2020.09.24 |
Backbone.js : 뷰를 다시 채우거나 다시 만드시겠습니까? (0) | 2020.09.24 |
Rails database.yml을 관리하는 방법 (0) | 2020.09.24 |