Skip to content

Commit 52dbd7a

Browse files
authored
Let pygmt.info load datetime columns into a str dtype array (#960)
Fixes problem with pygmt.info not being able to handle datetime64 inputs. I.e. `ValueError: could not convert string to float: '2021-01-01T12:34:56'` However, users will still need to use`pygmt.info(..., coltypes="0T")` until upstream issue at GenericMappingTools/gmt#4241 is resolved. Also added two extra unit tests using numpy datetime64 types. * Use common alias coltypes (f) in tests and make a note on the workaround
1 parent eb2bcc5 commit 52dbd7a

File tree

2 files changed

+32
-1
lines changed

2 files changed

+32
-1
lines changed

pygmt/src/info.py

+5-1
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,10 @@ def info(table, **kwargs):
7474
# instead of a raw string that is less useful.
7575
if result.startswith(("-R", "-T")): # e.g. -R0/1/2/3 or -T0/9/1
7676
result = result[2:].replace("/", " ")
77-
result = np.loadtxt(result.splitlines())
77+
try:
78+
result = np.loadtxt(result.splitlines())
79+
except ValueError:
80+
# Load non-numerical outputs in str type, e.g. for datetime
81+
result = np.loadtxt(result.splitlines(), dtype="str")
7882

7983
return result

pygmt/tests/test_info.py

+27
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,20 @@ def test_info_dataframe():
4141
assert output == expected_output
4242

4343

44+
def test_info_numpy_array_time_column():
45+
"""
46+
Make sure info works on a numpy.ndarray input with a datetime type.
47+
"""
48+
table = pd.date_range(start="2020-01-01", periods=5).to_numpy()
49+
# Please remove coltypes="0T" workaround after
50+
# https://github.com/GenericMappingTools/gmt/issues/4241 is resolved
51+
output = info(table=table, coltypes="0T")
52+
expected_output = (
53+
"<vector memory>: N = 5 <2020-01-01T00:00:00/2020-01-05T00:00:00>\n"
54+
)
55+
assert output == expected_output
56+
57+
4458
@pytest.mark.xfail(
4559
reason="UNIX timestamps returned instead of ISO datetime, should work on GMT 6.2.0 "
4660
"after https://github.com/GenericMappingTools/gmt/issues/4241 is resolved",
@@ -115,6 +129,19 @@ def test_info_per_column():
115129
)
116130

117131

132+
def test_info_per_column_with_time_inputs():
133+
"""
134+
Make sure the per_column option works with time inputs.
135+
"""
136+
table = pd.date_range(start="2020-01-01", periods=5).to_numpy()
137+
# Please remove coltypes="0T" workaround after
138+
# https://github.com/GenericMappingTools/gmt/issues/4241 is resolved
139+
output = info(table=table, per_column=True, coltypes="0T")
140+
npt.assert_equal(
141+
actual=output, desired=["2020-01-01T00:00:00", "2020-01-05T00:00:00"]
142+
)
143+
144+
118145
def test_info_spacing():
119146
"""
120147
Make sure the spacing option works.

0 commit comments

Comments
 (0)