Reputation: 15
I have to compare two time field strings represented like "[email protected]@EDT"
. How can i compare them most optimally in python?
I want to do >=
type comparsions on such fields which are of type string.
val1 = "[email protected]@EDT"
val2 = "[email protected]@EDT"
if val1 > = val2:
<do something>
Upvotes: 1
Views: 1650
Reputation: 26
import datetime
t=datetime.datetime.strptime("[email protected]@EDT","%Y%m%d@%H%M%S.%f@%Z")
datetime object supports direct compare using >=.
standard python lib may not handle timezones well ,you may need some third-party module like pytz
Upvotes: 1
Reputation: 1048
Something like the following should do the trick.
import time
val1 = "[email protected]@EDT"
val2 = "[email protected]@EDT"
a = time.strptime(val1, '%Y%m%d@%H%M%S.%f@%Z')
b = time.strptime(val2, '%Y%m%d@%H%M%S.%f@%Z')
if a >= b:
<do something>
Upvotes: 0
Reputation: 2513
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'
Upvotes: 0
Reputation: 1668
Use the datetime
module for this.
Use datetime.datetime.strptime
to convert the strings into dates then compare them using >=
.
Upvotes: 0