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())
3
  • 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. Commented May 11, 2015 at 4: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 stackoverflow.com/questions/1101508/… Commented May 11, 2015 at 4: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… Commented May 11, 2015 at 4:39

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.