Pergunta

I have two strings

s1 = "2013-11-21T07:45:51ZUTC+0000" # Europe
s2 = "2013-11-21T13:15:28ZUTC+0530" # India

I like to know the difference in seconds (should be 23 seconds). I tried:

from dateutil.parser import parse
dt1 = parse(s1)
dt2 = parse(s2)
(dt1-dt2).total_seconds()
-39577.0

This is not the correct result. What do I have to do to get the correct result? TIA!

Foi útil?

Solução

Given that your date string will be in the same format. You could help the parse function to figure out the correct date by removing the 'ZUTC' from the string. Like this:

from dateutil.parser import parse

s1 = "2013-11-21T07:45:51ZUTC+0000" # Europe
s2 = "2013-11-21T13:15:28ZUTC+0530" # India

def new_parse(string):
    return parse(string.replace('ZUTC', ''))

dt1 = new_parse(s1)
dt2 = new_parse(s2)
print (dt1-dt2).total_seconds()

Outras dicas

>>> import datetime
>>> str(datetime.datetime.strptime("2013-11-21T07:45:51ZUTC+0000", "%Y-%m-%dT%H:%M:%SZ%Z%z") - datetime.datetime.strptime("2013-11-21T13:15:28ZUTC+0530", "%Y-%m-%dT%H:%M:%SZ%Z%z"))
'0:00:23'

Actually 23 seconds.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top