_datetime.py 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. # coding=utf-8
  2. # Copyright 2022-present, the HuggingFace Inc. team.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. """Contains utilities to handle datetimes in Huggingface Hub."""
  16. from datetime import datetime, timezone
  17. def parse_datetime(date_string: str) -> datetime:
  18. """
  19. Parses a date_string returned from the server to a datetime object.
  20. This parser is a weak-parser is the sense that it handles only a single format of
  21. date_string. It is expected that the server format will never change. The
  22. implementation depends only on the standard lib to avoid an external dependency
  23. (python-dateutil). See full discussion about this decision on PR:
  24. https://github.com/huggingface/huggingface_hub/pull/999.
  25. Example:
  26. ```py
  27. > parse_datetime('2022-08-19T07:19:38.123Z')
  28. datetime.datetime(2022, 8, 19, 7, 19, 38, 123000, tzinfo=timezone.utc)
  29. ```
  30. Args:
  31. date_string (`str`):
  32. A string representing a datetime returned by the Hub server.
  33. String is expected to follow '%Y-%m-%dT%H:%M:%S.%fZ' pattern.
  34. Returns:
  35. A python datetime object.
  36. Raises:
  37. :class:`ValueError`:
  38. If `date_string` cannot be parsed.
  39. """
  40. try:
  41. # Normalize the string to always have 6 digits of fractional seconds
  42. if date_string.endswith("Z"):
  43. # Case 1: No decimal point (e.g., "2024-11-16T00:27:02Z")
  44. if "." not in date_string:
  45. # No fractional seconds - insert .000000
  46. date_string = date_string[:-1] + ".000000Z"
  47. # Case 2: Has decimal point (e.g., "2022-08-19T07:19:38.123456789Z")
  48. else:
  49. # Get the fractional and base parts
  50. base, fraction = date_string[:-1].split(".")
  51. # fraction[:6] takes first 6 digits and :0<6 pads with zeros if less than 6 digits
  52. date_string = f"{base}.{fraction[:6]:0<6}Z"
  53. return datetime.strptime(date_string, "%Y-%m-%dT%H:%M:%S.%fZ").replace(tzinfo=timezone.utc)
  54. except ValueError as e:
  55. raise ValueError(
  56. f"Cannot parse '{date_string}' as a datetime. Date string is expected to"
  57. " follow '%Y-%m-%dT%H:%M:%S.%fZ' pattern."
  58. ) from e