|
16 | 16 | from pathlib import Path
|
17 | 17 | from typing import Any, Literal
|
18 | 18 |
|
| 19 | +import numpy as np |
19 | 20 | import xarray as xr
|
20 | 21 | from pygmt._typing import PathLike
|
21 | 22 | from pygmt.encodings import charset
|
@@ -816,6 +817,30 @@ def sequence_join(
|
816 | 817 | ['1/2', '3/4']
|
817 | 818 | >>> sequence_join([1, 2, 3, 4], separator=",")
|
818 | 819 | '1,2,3,4'
|
| 820 | +
|
| 821 | + >>> # Join a sequence of datetime-like objects into a string. |
| 822 | + >>> import datetime |
| 823 | + >>> import numpy as np |
| 824 | + >>> import pandas as pd |
| 825 | + >>> import xarray as xr |
| 826 | + >>> sequence_join( |
| 827 | + ... [ |
| 828 | + ... datetime.date(2010, 1, 1), |
| 829 | + ... np.datetime64("2010-01-01T16:00:00"), |
| 830 | + ... np.array("2010-03-01T00:00:00", dtype=np.datetime64), |
| 831 | + ... ], |
| 832 | + ... sep="/", |
| 833 | + ... ) |
| 834 | + '2010-01-01/2010-01-01T16:00:00/2010-03-01T00:00:00' |
| 835 | + >>> sequence_join( |
| 836 | + ... [ |
| 837 | + ... datetime.datetime(2010, 3, 1), |
| 838 | + ... pd.Timestamp("2015-01-01T12:00:00.123456789"), |
| 839 | + ... xr.DataArray(data=np.datetime64("2005-01-01T08:00:00", "ns")), |
| 840 | + ... ], |
| 841 | + ... sep="/", |
| 842 | + ... ) |
| 843 | + '2010-03-01T00:00:00.000000/2015-01-01T12:00:00.123456/2005-01-01T08:00:00.000000000' |
819 | 844 | """
|
820 | 845 | # Return the original value if it is not a sequence (e.g., None, bool, or str).
|
821 | 846 | if not is_nonstr_iter(value):
|
@@ -848,7 +873,17 @@ def sequence_join(
|
848 | 873 | f"but got {len(value)} values."
|
849 | 874 | )
|
850 | 875 | raise GMTInvalidInput(msg)
|
851 |
| - return sep.join(str(v) for v in value) |
| 876 | + # 'str(v)' produces a string like '2024-01-01 00:00:00' for some datetime-like |
| 877 | + # objects (e.g., datetime.datetime, pandas.Timestamp), which contains a space. |
| 878 | + # If so, use np.datetime_as_string to convert it to ISO 8601 string format |
| 879 | + # YYYY-MM-DDThh:mm:ss.ffffff. |
| 880 | + _values = [ |
| 881 | + np.datetime_as_string(np.asarray(item, dtype="datetime64")) |
| 882 | + if " " in (s := str(item)) |
| 883 | + else s |
| 884 | + for item in value |
| 885 | + ] |
| 886 | + return sep.join(_values) # type: ignore[arg-type] |
852 | 887 |
|
853 | 888 | # Now it must be a 2-D sequence.
|
854 | 889 | if ndim == 1:
|
|
0 commit comments