我必须比较两个时间字段字符串,如"[email protected]@EDT"
。我如何在Python中最优化地比较它们?我想对类型的字符串进行比较。如何比较python中的两个时间字段
val1 = "[email protected]@EDT"
val2 = "[email protected]@EDT"
if val1 > = val2:
<do something>
我必须比较两个时间字段字符串,如"[email protected]@EDT"
。我如何在Python中最优化地比较它们?我想对类型的字符串进行比较。如何比较python中的两个时间字段
val1 = "[email protected]@EDT"
val2 = "[email protected]@EDT"
if val1 > = val2:
<do something>
import datetime
t=datetime.datetime.strptime("[email protected]@EDT","%Y%m%[email protected]%H%M%S.%[email protected]%Z")
DateTime对象支持直接比较使用> =。
标准Python的lib可能无法处理时区好,你可能需要一些第三方的模块状pytz
使用datetime
模块这一点。
使用datetime.datetime.strptime
将字符串转换为日期,然后使用>=
进行比较。
import time
from time import gmtime, strftime
currentTime=strftime("%Y-%m-%d %H:%M:%S", gmtime())
print currentTime
time.sleep(5)
SecondTime=strftime("%Y-%m-%d %H:%M:%S", gmtime())
print SecondTime
from dateutil.parser import parse
parseSecondTime = parse(SecondTime)
parseCurrentTime = parse(currentTime)
diffOfTime = parseSecondTime - parseCurrentTime
timeDifference=diffOfTime.total_seconds()
print timeDifference
if timeDifference>0:
print 'SecondTime is greater'
else:
print 'Current Time is Greater'
像下面这样的东西应该可以做到。
import time
val1 = "[email protected]@EDT"
val2 = "[email protected]@EDT"
a = time.strptime(val1, '%Y%m%[email protected]%H%M%S.%[email protected]%Z')
b = time.strptime(val2, '%Y%m%[email protected]%H%M%S.%[email protected]%Z')
if a >= b:
<do something>
什么问题?你可以在Python中做这种比较。 – orange 2014-12-11 05:36:26