gfw.common.datetime#

Utility functions for working with datetime objects and timezones.

Functions

datetime_from_date

Creates datetime from a datetime.date object.

datetime_from_isoformat

Converts a datetime string to a timezone-aware datetime.

datetime_from_string

Extracts a zone-aware datetime from a string.

datetime_from_timestamp

Converts a Unix timestamp to a timezone-aware datetime.

datetime_from_timestamp(ts, tz=datetime.timezone.utc)[source]#

Converts a Unix timestamp to a timezone-aware datetime.

By default, the timestamp is converted to UTC. If you need a different timezone, specify it using the tz argument.

Parameters:
  • ts (int | float) – The Unix timestamp to convert.

  • tz (tzinfo) – The timezone to apply. Defaults to UTC.

Returns:

A timezone-aware datetime

object corresponding to the given timestamp.

Return type:

datetime

datetime_from_isoformat(s, tz=datetime.timezone.utc)[source]#

Converts a datetime string to a timezone-aware datetime.

Parameters:
  • s (str) – The string to convert, in ISO 8601 format (e.g., 2025-04-30T10:20:30).

  • tz (tzinfo) – The timezone to apply to the resulting datetime, if not present. Defaults to UTC.

Returns:

A timezone-aware datetime object.

Return type:

datetime

datetime_from_date(d, t=None, tz=datetime.timezone.utc)[source]#

Creates datetime from a datetime.date object.

Parameters:
  • d (date) – Date part of the datetime.

  • t (time | None) – Optional time part.

  • tz (timezone) – Timezone for the resulting datetime. Defaults to UTC.

Returns:

A timezone-aware datetime object.

Return type:

datetime

datetime_from_string(s, date_format='%Y-%m-%d', time_format='%H_%M_%SZ', allow_no_time=True, tz=datetime.timezone.utc)[source]#

Extracts a zone-aware datetime from a string.

Parameters:
  • s (str) – The string containing the datetime to extract.

  • date_format (str) – The strftime/strptime format of the date part. Defaults to %Y-%m-%d.

  • time_format (str) – The strftime/strptime format of the time part. Defaults to %H_%M_%SZ.

  • allow_no_time (bool) – If True, allows input strings with no time information.

  • tz (timezone) – The timezone to apply if the parsed datetime has no tzinfo. Defaults to UTC.

Raises:

ValueError

  • When date is not found in the input string. - When time is not found in the input string and allow_no_time is False.

Returns:

A timezone-aware datetime object.

Return type:

datetime