Coretex
date.py
1 # Copyright (C) 2023 Coretex LLC
2 
3 # This file is part of Coretex.ai
4 
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU Affero General Public License as
7 # published by the Free Software Foundation, either version 3 of the
8 # License, or (at your option) any later version.
9 
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU Affero General Public License for more details.
14 
15 # You should have received a copy of the GNU Affero General Public License
16 # along with this program. If not, see <https://www.gnu.org/licenses/>.
17 
18 from datetime import datetime, timezone
19 
20 
21 # Time zone used for dates on Coretex backend
22 TIME_ZONE = timezone.utc
23 
24 # Date format used by Coretex backend
25 DATE_FORMAT = "%Y-%m-%d %H:%M:%S.%f%z"
26 
27 CORETEX_DATE_FORMATS = [
28  DATE_FORMAT,
29  "%Y-%m-%dT%H:%M:%S.%f%z",
30  "%Y-%m-%d %H:%M:%S%z"
31 ]
32 
33 
34 def decodeDate(value: str) -> datetime:
35  """
36  Converts the date to a format used by Coretex
37 
38  Returns
39  -------
40  datetime -> object whose datetime is represented using the Coretex datetime format
41  """
42 
43  for format in CORETEX_DATE_FORMATS:
44  try:
45  return datetime.strptime(value, format)
46  except ValueError:
47  continue
48 
49  for format in CORETEX_DATE_FORMATS:
50  try:
51  # Python's datetime library requires UTC minutes to always
52  # be present in the date in either of those 2 formats:
53  # - +HHMM
54  # - +HH:MM
55  # BUT coretex API sends it in one of those formats:
56  # - +HH
57  # - +HH:MM (only if the minutes have actual value)
58  # so we need to handle the first case where minutes
59  # are not present by adding them manually
60  return datetime.strptime(f"{value}00", format)
61  except ValueError:
62  continue
63 
64  raise ValueError(f"Failed to convert \"{value}\" to any of the supported formats \"{CORETEX_DATE_FORMATS}\"")