Skip to content

tconvert() can't handle Quantities

The gwpy.time.tconvert method (on top of gwpy.time.to_gps) can't handle astropy.units.Quantity objects, even if they have units of 's':

>>> from astropy.units import Quantity
>>> from gwpy.time import tconvert
>>> tconvert(Quantity(12345, 's'))
>>> Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/duncan/Library/Python/2.7/lib/python/site-packages/gwpy-0.1a10.dev833-py2.7.egg/gwpy/time/_tconvert.py", line 64, in tconvert
    return to_gps(gpsordate)
  File "/Users/duncan/Library/Python/2.7/lib/python/site-packages/gwpy-0.1a10.dev833-py2.7.egg/gwpy/time/_tconvert.py", line 131, in to_gps
    return LIGOTimeGPS(t)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/glue/lal.py", line 141, in __init__
    raise TypeError(seconds)
TypeError: 12345.0 s

The following patch can be applied to fix the TypeError:

diff --git a/gwpy/time/_tconvert.py b/gwpy/time/_tconvert.py
index 0ef2b26..4c48efb 100644
--- a/gwpy/time/_tconvert.py
+++ b/gwpy/time/_tconvert.py
@@ -26,6 +26,8 @@ import datetime

 from dateutil import parser as dateparser

+from astropy.units import Quantity
+
 from .. import version
 from . import (Time, LIGOTimeGPS)

@@ -127,6 +129,9 @@ def to_gps(t, *args, **kwargs):
     # and then into LIGOTimeGPS
     if isinstance(t, Time):
         return time_to_gps(t)
+    # extract Quantity to just float
+    if isinstance(t, Quantity):
+        t = t.to('s').value
     # if all else fails...
     return LIGOTimeGPS(t)