Repository: OceanParcels/parcels (python)

Issue:
FieldSet.from_data does not accept np.datetime64 time objects
While we support `np.datetime64` throughout most of Parcels, these are not accepted in `FieldSet.from_data()` yet, which assumes that the `time` vector contains either floats or ints.

Pull request:
Adding support for np.datetime64 in Field.from_data()
This fixes #586

Patch:
diff --git a/parcels/fieldset.py b/parcels/fieldset.py
index 4fae531f..c94db459 100644
--- a/parcels/fieldset.py
+++ b/parcels/fieldset.py
@@ -86,7 +86,13 @@ class FieldSet(object):
             lat = dims['lat']
             depth = np.zeros(1, dtype=np.float32) if 'depth' not in dims else dims['depth']
             time = np.zeros(1, dtype=np.float64) if 'time' not in dims else dims['time']
-            grid = Grid.create_grid(lon, lat, depth, time, time_origin=TimeConverter(), mesh=mesh)
+            time = np.array(time) if not isinstance(time, np.ndarray) else time
+            if isinstance(time[0], np.datetime64):
+                time_origin = TimeConverter(time[0])
+                time = np.array([time_origin.reltime(t) for t in time])
+            else:
+                time_origin = TimeConverter(0)
+            grid = Grid.create_grid(lon, lat, depth, time, time_origin=time_origin, mesh=mesh)
             if 'creation_log' not in kwargs.keys():
                 kwargs['creation_log'] = 'from_data'
 


Test patch:
diff --git a/tests/test_fieldset.py b/tests/test_fieldset.py
index 8b32b7ec..c06c9242 100644
--- a/tests/test_fieldset.py
+++ b/tests/test_fieldset.py
@@ -42,6 +42,19 @@ def test_fieldset_from_data(xdim, ydim):
     assert np.allclose(fieldset.V.data[0, :], data['V'], rtol=1e-12)
 
 
+@pytest.mark.parametrize('ttype', ['float', 'datetime64'])
+@pytest.mark.parametrize('tdim', [1, 20])
+def test_fieldset_from_data_timedims(ttype, tdim):
+    data, dimensions = generate_fieldset(10, 10, tdim=tdim)
+    if ttype == 'float':
+        dimensions['time'] = np.linspace(0, 5, tdim)
+    else:
+        dimensions['time'] = [np.datetime64('2018-01-01') + np.timedelta64(t, 'D') for t in range(tdim)]
+    fieldset = FieldSet.from_data(data, dimensions)
+    for i, dtime in enumerate(dimensions['time']):
+        assert fieldset.U.grid.time_origin.fulltime(fieldset.U.grid.time[i]) == dtime
+
+
 @pytest.mark.parametrize('xdim', [100, 200])
 @pytest.mark.parametrize('ydim', [100, 50])
 def test_fieldset_from_data_different_dimensions(xdim, ydim, zdim=4, tdim=2):