2

How to find the difference between 2 dates in seconds with timezone only using the python standard modules such as datetime, time etc.. not with dateutil, pytz etc... This is not a duplicate question.

from datetime import datetime
t2 = datetime.strptime('Sun 4 May 2015 13:54:36 -0600', "%a %d %b %Y %H:%M:%S %z")
t1 = datetime.strptime('Sun 4 May 2015 13:54:36 -0000', "%a %d %b %Y %H:%M:%S %z")
diff = (t2 - t1).seconds
print diff

But it gives me error like, ValueError: 'z' is a bad directive in format '%a %d %b %Y %H:%M:%S %z'

I guess it is a naive object. So how to find the difference for naive object using datetime or time module. Do we need to create our own function to do that?

Simple inputs:

'Sun 10 May 2015 17:56:26 +0430'
'Sat 09 May 2015 15:56:26 +0000'

If i could parse the date like this using,

from datetime import datetime
t2 = datetime.strptime('Sun 4 May 2015 13:54:36', "%a %d %b %Y %H:%M:%S")
t1 = datetime.strptime('Sun 4 May 2015 13:54:36', "%a %d %b %Y %H:%M:%S")
diff = (t2 - t1).seconds
print diff

Then how to handle the timezone info? Any hint will be helpful.

I could easily do this with dateutil module like

from dateutil import parser
t1 = parser.parse("Sun 4 May 2015 13:54:36 -0600")  
t2 = parser.parse("Sun 4 May 2015 13:54:36 -0000")  
diff = t1 - t2
print int(diff.total_seconds())
cracker
  • 445
  • 1
  • 5
  • 10
  • 1
    I believe that in Python 2.x (and early 3.x), `%z` is only supported for `strftime`, not `strptime`—although on some platforms (where the underlying C function supports it) it may work anyway. If so means if you don't want to upgrade to 3.x or use a third-party library, you'll have to split off the tzoffset, parse it yourself, and either (a) adjust the datetimes, or (b) an offset-only timezone object and apply it, creating aware datetimes. – abarnert May 11 '15 at 04:23
  • `%z` doens't work because it depends on the OS. Not because it's a naive object. Take a look here how to fix http://stackoverflow.com/questions/1101508/how-to-parse-dates-with-0400-timezone-string-in-python/23122493#23122493 – Martin Konecny May 11 '15 at 04:24
  • 1
    @MartinKonecny: I think this counts as a dup of that question. Even though the question doesn't specify no third party libs, and the accepted answer uses `dateutil`, you'd be hard pressed to find a better answer than J.F. Sebastian's for this… – abarnert May 11 '15 at 04:39

0 Answers0