diff --git a/pygmt/helpers/utils.py b/pygmt/helpers/utils.py index b16885689ff..6548a0bb8c9 100644 --- a/pygmt/helpers/utils.py +++ b/pygmt/helpers/utils.py @@ -2,6 +2,7 @@ Utilities and common tasks for wrapping the GMT modules. """ +import contextlib import io import os import shutil @@ -920,14 +921,13 @@ def sequence_join( # or integer number for timedelta64. _values = [] for item in value: + _value = str(item) if isinstance(item, np.timedelta64): # Convert timedelta64 to numeric value - _values.append(str(item.astype(int))) - elif " " in str(item): - _values.append( - np.datetime_as_string(np.asarray(item, dtype="datetime64")) # type: ignore[arg-type] - ) - else: - _values.append(str(item)) + _value = str(item.astype(int)) + elif " " in _value: # Likely a datetime-like object. + with contextlib.suppress(ValueError): + _value = np.datetime_as_string(np.asarray(item, dtype="datetime64")) # type: ignore[assignment] + _values.append(_value) return sep.join(_values) # type: ignore[arg-type] # Now it must be a 2-D sequence. diff --git a/pygmt/tests/test_helpers.py b/pygmt/tests/test_helpers.py index 09d65eb345c..fdb6380d73e 100644 --- a/pygmt/tests/test_helpers.py +++ b/pygmt/tests/test_helpers.py @@ -7,6 +7,7 @@ from pathlib import Path from unittest.mock import patch +import pandas as pd import pytest import xarray as xr from pygmt import Figure @@ -17,6 +18,7 @@ build_arg_list, kwargs_to_strings, launch_external_viewer, + sequence_join, unique_name, ) from pygmt.helpers.testing import load_static_earth_relief, skip_if_no @@ -151,6 +153,22 @@ def test_args_in_kwargs(): assert not args_in_kwargs(args=failing_args, kwargs=kwargs) +def test_sequence_join_strings_with_spaces(): + """ + Test that sequence_join handles strings with spaces and datetime-like objects. + Regression test for https://github.com/GenericMappingTools/pygmt/issues/4960. + """ + assert sequence_join(["W", "E", "S", "North Pole"], sep=",", size=4) == ( + "W,E,S,North Pole" + ) + assert sequence_join(["2010-01-01 12:00:00", "2010-01-02"], sep="/") == ( + "2010-01-01T12:00:00/2010-01-02" + ) + assert sequence_join([pd.Timestamp("2010-01-01 12:00:00"), 1], sep="/") == ( + "2010-01-01T12:00:00.000000/1" + ) + + def test_skip_if_no(): """ Test that the skip_if_no helper testing function returns a pytest.mask.skipif mark