Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add timespec to datetime_to_str util function. #929

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 7,7 @@
- Update Grid Extension support to v1.1.0 and fix issue with grid:code prefix validation ([#925](https://github.com/stac-utils/pystac/pull/925))
- Adds custom `header` support to `DefaultStacIO` ([#889](https://github.com/stac-utils/pystac/pull/889))
- Python 3.11 checks in CI ([#908](https://github.com/stac-utils/pystac/pull/908))
- Add the optional argument timespec to datetime_to_str function in utils ([#929](https://github.com/stac-utils/pystac/pull/929))

### Removed

Expand Down
8 changes: 6 additions & 2 deletions pystac/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -299,22 299,26 @@ def is_absolute_href(href: str) -> bool:
return parsed.scheme != "" or _pathlib.isabs(parsed.path)


def datetime_to_str(dt: datetime) -> str:
def datetime_to_str(dt: datetime, timespec: str = "auto") -> str:
"""Converts a :class:`datetime.datetime` instance to an ISO8601 string in the
`RFC 3339, section 5.6
<https://datatracker.ietf.org/doc/html/rfc3339#section-5.6>`__ format required by
the :stac-spec:`STAC Spec <master/item-spec/common-metadata.md#date-and-time>`.

Args:
dt : The datetime to convert.
timespec: An optional argument that specifies the number of additional
terms of the time to include. Valid options are 'auto', 'hours',
'minutes', 'seconds', 'milliseconds' and 'microseconds'. The default value
is 'auto'.

Returns:
str: The ISO8601 (RFC 3339) formatted string representing the datetime.
"""
if dt.tzinfo is None:
dt = dt.replace(tzinfo=timezone.utc)

timestamp = dt.isoformat()
timestamp = dt.isoformat(timespec=timespec)
zulu = " 00:00"
if timestamp.endswith(zulu):
timestamp = "{}Z".format(timestamp[: -len(zulu)])
Expand Down
24 changes: 24 additions & 0 deletions tests/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -281,6 281,30 @@ def test_datetime_to_str(self) -> None:
got = utils.datetime_to_str(dt)
self.assertEqual(expected, got)

def test_datetime_to_str_with_microseconds_timespec(self) -> None:
cases = (
(
"timezone naive, assume utc",
datetime(2000, 1, 1, 0, 0, 0, 0),
"2000-01-01T00:00:00.000000Z",
),
(
"timezone aware, utc",
datetime(2000, 1, 1, 0, 0, 0, 0, tzinfo=timezone.utc),
"2000-01-01T00:00:00.000000Z",
),
(
"timezone aware, utc -7",
datetime(2000, 1, 1, 0, 0, 0, 0, tzinfo=timezone(timedelta(hours=-7))),
"2000-01-01T00:00:00.000000-07:00",
),
)

for title, dt, expected in cases:
with self.subTest(title=title):
got = utils.datetime_to_str(dt, timespec="microseconds")
self.assertEqual(expected, got)

def test_str_to_datetime(self) -> None:
def _set_tzinfo(tz_str: Optional[str]) -> None:
if tz_str is None:
Expand Down