Calculate time difference using python
Question: I am wondering if there is a way or builtin library available to find the
difference in time from two string input.

What I mean is, if I have 2 input strings:

  1. '2013-10-05T01:21:07Z'
  2. '2013-10-05T01:21:16Z'

how can I can calculate the difference in time and print it as output.

I know it sounds a bit silly but any help on this is appreciated.


Answer: You seem to be using an ISO 8601 formatted
[dateTime](http://books.xmlschemata.org/relaxng/ch19-77049.html). This format
is used in many places, including the GPS eXchange Format.

    
    
    [-]CCYY-MM-DDThh:mm:ss[Z|(+|-)hh:mm]
    

## Using datetime:

    
    
    import datetime
    a = datetime.datetime.strptime("2013-10-05T01:21:07Z", "%Y-%m-%dT%H:%M:%SZ")
    b = datetime.datetime.strptime("2013-10-05T01:21:16Z", "%Y-%m-%dT%H:%M:%SZ")
    c = b - a
    print(c)
    

**Advantages:**

  * Built-in to Python Standard Library
  * Object-oriented interface

**Disadvantages:**

  * Need to manually handle other valid ISO 8601 representations such as '2013-10-05T01:21:16+00:00'
  * Throws exception for leap seconds such as '2012-06-30T23:59:60Z'

## Using python-dateutil:

    
    
    import dateutil.parser
    a = dateutil.parser.parse("2013-10-05T01:21:07Z")
    b = dateutil.parser.parse("2013-10-05T01:21:16Z")
    c = b - a
    print(c)
    

**Advantages:**

  * Automagically handles pretty much any time format

**Disadvantages:**

  * Needs python-dateutil library (pip install python-dateutil)
  * Throws exception for leap seconds such as '2012-06-30T23:59:60Z'

## Using time.strptime and time.mktime as suggested by
[Alfe](http://stackoverflow.com/a/23886181/1703216)

**Advantages:**

  * Built-in to Python Standard Library
  * Can parse leap seconds such as '2012-06-30T23:59:60Z'

**Disadvantages:**

  * Need to manually handle other valid ISO 8601 representations such as '2013-10-05T01:21:16+00:00'
  * Loss of one leap second between '2012-06-30T23:59:60Z' and '2012-07-01T00:00:00Z' (unavoidable without knowing when leap seconds will next occur)

