-
Notifications
You must be signed in to change notification settings - Fork 3k
Python: Refactor to use common decimal and datetime util #4480
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
Merged
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,65 @@ | ||
| # Licensed to the Apache Software Foundation (ASF) under one | ||
| # or more contributor license agreements. See the NOTICE file | ||
| # distributed with this work for additional information | ||
| # regarding copyright ownership. The ASF licenses this file | ||
| # to you under the Apache License, Version 2.0 (the | ||
| # "License"); you may not use this file except in compliance | ||
| # with the License. You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, | ||
| # software distributed under the License is distributed on an | ||
| # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | ||
| # KIND, either express or implied. See the License for the | ||
| # specific language governing permissions and limitations | ||
| # under the License. | ||
| """Helper methods for working with date/time representations | ||
| """ | ||
| import re | ||
| from datetime import date, datetime, time | ||
|
|
||
| EPOCH_DATE = date.fromisoformat("1970-01-01") | ||
| EPOCH_TIMESTAMP = datetime.fromisoformat("1970-01-01T00:00:00.000000") | ||
| ISO_TIMESTAMP = re.compile(r"\d\d\d\d-\d\d-\d\dT\d\d:\d\d:\d\d(.\d{1,6})?") | ||
| EPOCH_TIMESTAMPTZ = datetime.fromisoformat("1970-01-01T00:00:00.000000+00:00") | ||
| ISO_TIMESTAMPTZ = re.compile(r"\d\d\d\d-\d\d-\d\dT\d\d:\d\d:\d\d(.\d{1,6})?[-+]\d\d:\d\d") | ||
|
|
||
|
|
||
| def micros_to_days(timestamp: int) -> int: | ||
| """Converts a timestamp in microseconds to a date in days""" | ||
| return (datetime.fromtimestamp(timestamp / 1_000_000) - EPOCH_TIMESTAMP).days | ||
|
|
||
|
|
||
| def date_to_days(date_str: str) -> int: | ||
| """Converts an ISO-8601 formatted date to days from 1970-01-01""" | ||
| return (date.fromisoformat(date_str) - EPOCH_DATE).days | ||
|
|
||
|
|
||
| def time_to_micros(time_str: str) -> int: | ||
| """Converts an ISO-8601 formatted time to microseconds from midnight""" | ||
| t = time.fromisoformat(time_str) | ||
| return (((t.hour * 60 + t.minute) * 60) + t.second) * 1_000_000 + t.microsecond | ||
|
|
||
|
|
||
| def datetime_to_micros(dt: datetime) -> int: | ||
| """Converts a datetime to microseconds from 1970-01-01T00:00:00.000000""" | ||
| if dt.tzinfo: | ||
| delta = dt - EPOCH_TIMESTAMPTZ | ||
| else: | ||
| delta = dt - EPOCH_TIMESTAMP | ||
| return (delta.days * 86400 + delta.seconds) * 1_000_000 + delta.microseconds | ||
|
|
||
|
|
||
| def timestamp_to_micros(timestamp_str: str) -> int: | ||
| """Converts an ISO-9601 formatted timestamp without zone to microseconds from 1970-01-01T00:00:00.000000""" | ||
| if ISO_TIMESTAMP.fullmatch(timestamp_str): | ||
| return datetime_to_micros(datetime.fromisoformat(timestamp_str)) | ||
| raise ValueError(f"Invalid timestamp without zone: {timestamp_str} (must be ISO-8601)") | ||
|
|
||
|
|
||
| def timestamptz_to_micros(timestamptz_str: str) -> int: | ||
| """Converts an ISO-8601 formatted timestamp with zone to microseconds from 1970-01-01T00:00:00.000000+00:00""" | ||
| if ISO_TIMESTAMPTZ.fullmatch(timestamptz_str): | ||
| return datetime_to_micros(datetime.fromisoformat(timestamptz_str)) | ||
| raise ValueError(f"Invalid timestamp with zone: {timestamptz_str} (must be ISO-8601)") |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,77 @@ | ||
| # Licensed to the Apache Software Foundation (ASF) under one | ||
| # or more contributor license agreements. See the NOTICE file | ||
| # distributed with this work for additional information | ||
| # regarding copyright ownership. The ASF licenses this file | ||
| # to you under the Apache License, Version 2.0 (the | ||
| # "License"); you may not use this file except in compliance | ||
| # with the License. You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, | ||
| # software distributed under the License is distributed on an | ||
| # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | ||
| # KIND, either express or implied. See the License for the | ||
| # specific language governing permissions and limitations | ||
| # under the License. | ||
|
|
||
| """Helper methods for working with Python Decimals | ||
| """ | ||
| from decimal import Decimal | ||
| from typing import Union | ||
|
|
||
|
|
||
| def decimal_to_unscaled(value: Decimal) -> int: | ||
| """Get an unscaled value given a Decimal value | ||
|
|
||
| Args: | ||
| value (Decimal): A Decimal instance | ||
|
|
||
| Returns: | ||
| int: The unscaled value | ||
| """ | ||
| sign, digits, _ = value.as_tuple() | ||
| return int(Decimal((sign, digits, 0)).to_integral_value()) | ||
|
|
||
|
|
||
| def unscaled_to_decimal(unscaled: int, scale: int) -> Decimal: | ||
| """Get a scaled Decimal value given an unscaled value and a scale | ||
|
|
||
| Args: | ||
| unscaled (int): An unscaled value | ||
| scale (int): A scale to set for the returned Decimal instance | ||
|
|
||
| Returns: | ||
| Decimal: A scaled Decimal instance | ||
| """ | ||
| sign, digits, _ = Decimal(unscaled).as_tuple() | ||
| return Decimal((sign, digits, -scale)) | ||
|
|
||
|
|
||
| def bytes_required(value: Union[int, Decimal]) -> int: | ||
| """Returns the minimum number of bytes needed to serialize a decimal or unscaled value | ||
|
|
||
| Args: | ||
| value (int | Decimal): a Decimal value or unscaled int value | ||
|
|
||
| Returns: | ||
| int: the minimum number of bytes needed to serialize the value | ||
| """ | ||
| if isinstance(value, int): | ||
| return (value.bit_length() + 7) // 8 | ||
| elif isinstance(value, Decimal): | ||
| return (decimal_to_unscaled(value).bit_length() + 7) // 8 | ||
|
|
||
| raise ValueError(f"Unsupported value: {value}") | ||
|
|
||
|
|
||
| def decimal_to_bytes(value: Decimal) -> bytes: | ||
| """Returns a byte representation of a decimal | ||
|
|
||
| Args: | ||
| value (Decimal): a decimal value | ||
| Returns: | ||
| bytes: the unscaled value of the Decimal as bytes | ||
| """ | ||
| unscaled_value = decimal_to_unscaled(value) | ||
| return unscaled_value.to_bytes(bytes_required(unscaled_value), byteorder="big", signed=True) | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.