Skip to content

Commit

Permalink
Allow datetime inputs to region argument (#562)
Browse files Browse the repository at this point in the history
Includes support for:
- Python datetime objects
- np.datetime64
- pandas.Timestamp
- xarray.DataArray with datetime64 dtype
  • Loading branch information
weiji14 authored Aug 16, 2020
1 parent 2ddbb0e commit 4939ee2
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 4 deletions.
35 changes: 32 additions & 3 deletions pygmt/helpers/decorators.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
import textwrap
import functools

import numpy as np

from .utils import is_nonstr_iter
from ..exceptions import GMTInvalidInput

Expand Down Expand Up @@ -302,6 +304,23 @@ def kwargs_to_strings(convert_bools=True, **conversions):
>>> module(123, bla=(1, 2, 3), foo=True, A=False, i=(5, 6))
{'bla': (1, 2, 3), 'foo': '', 'i': '5,6'}
args: 123
>>> import datetime
>>> module(
... R=[
... np.datetime64("2010-01-01T16:00:00"),
... datetime.datetime(2020, 1, 1, 12, 23, 45),
... ]
... )
{'R': '2010-01-01T16:00:00/2020-01-01T12:23:45.000000'}
>>> import pandas as pd
>>> import xarray as xr
>>> module(
... R=[
... xr.DataArray(data=np.datetime64("2005-01-01T08:00:00")),
... pd.Timestamp("2015-01-01T12:00:00.123456789"),
... ]
... )
{'R': '2005-01-01T08:00:00.000000000/2015-01-01T12:00:00.123456'}
"""
valid_conversions = [
Expand Down Expand Up @@ -338,9 +357,19 @@ def new_module(*args, **kwargs):
value = kwargs[arg]
issequence = fmt in separators
if issequence and is_nonstr_iter(value):
kwargs[arg] = separators[fmt].join(
"{}".format(item) for item in value
)
for index, item in enumerate(value):
try:
# check if there is a space " " when converting
# a pandas.Timestamp/xr.DataArray to a string.
# If so, use np.datetime_as_string instead.
assert " " not in str(item)
except AssertionError:
# convert datetime-like item to ISO 8601
# string format like YYYY-MM-DDThh:mm:ss.ffffff
value[index] = np.datetime_as_string(
np.asarray(item, dtype=np.datetime64)
)
kwargs[arg] = separators[fmt].join(f"{item}" for item in value)
# Execute the original function and return its output
return module_func(*args, **kwargs)

Expand Down
11 changes: 10 additions & 1 deletion pygmt/tests/test_plot.py
Original file line number Diff line number Diff line change
Expand Up @@ -294,7 +294,16 @@ def test_plot_scalar_xy():
def test_plot_datetime():
"""Test various datetime input data"""
fig = Figure()
fig.basemap(projection="X15c/5c", region="2010-01-01/2020-01-01/0/10", frame=True)
fig.basemap(
projection="X15c/5c",
region=[
np.array("2010-01-01T00:00:00", dtype=np.datetime64),
pd.Timestamp("2020-01-01"),
0,
10,
],
frame=True,
)

# numpy.datetime64 types
x = np.array(
Expand Down

0 comments on commit 4939ee2

Please sign in to comment.