python-time-functions 2.1.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,8 @@
1
+ Metadata-Version: 2.4
2
+ Name: python_time_functions
3
+ Version: 2.1.1
4
+ Summary: Common Python functions for time handling
5
+ Author-email: Corne Bester <corne.bester@gmail.com>
6
+ License-Expression: MIT
7
+ License-File: LICENSE
8
+ Dynamic: license-file
@@ -0,0 +1,46 @@
1
+ # python_time_functions
2
+
3
+ example
4
+
5
+ ```
6
+ from datetime import datetime, timezone
7
+ from modules.time_functions import get_timestamp_unix_millis
8
+ # OR
9
+ from time_functions import get_timestamp_unix_millis
10
+ # OR
11
+ import time_functions
12
+
13
+ timestamp = datetime.now(timezone.utc)
14
+ unix_millis = get_timestamp_unix_millis(timestamp) # create unix timestamp from obj above
15
+
16
+ ```
17
+
18
+ ## local dev
19
+
20
+ pip install pytest build
21
+
22
+ ## test
23
+
24
+ pytest
25
+
26
+ ## build ( create dist artifacts )
27
+
28
+ python -m build
29
+
30
+ ## install from location
31
+
32
+ python -m pip install "C:\Users\corne\Documents\GitHub\python_time_functions\dist\pythom_time_functions-2.1.0-py3-none-any.whl"
33
+
34
+
35
+ ### other
36
+
37
+ pip3 freeze > requirements.txt
38
+
39
+ ## bad formats I dreamed up for iot/psql. fix with sanitizer fx
40
+
41
+ >>> time_functions.timestamp_sanitizer_psql(1729755232184)
42
+ 1729755232.184
43
+ >>> time_functions.timestamp_sanitizer_psql(1729765227856.3)
44
+ 1729765227.856
45
+ >>> time_functions.timestamp_sanitizer_psql(1729765228327.051)
46
+ 1729765228.327
@@ -0,0 +1,14 @@
1
+ [build-system]
2
+ requires = ["setuptools>=65.5.0"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "python_time_functions"
7
+ version = "2.1.1"
8
+ description = "Common Python functions for time handling"
9
+ authors = [{name = "Corne Bester", email = "corne.bester@gmail.com"}]
10
+ dependencies = [
11
+ ]
12
+
13
+ license = "MIT"
14
+ license-files = ["LICEN[CS]E*"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,8 @@
1
+ Metadata-Version: 2.4
2
+ Name: python_time_functions
3
+ Version: 2.1.1
4
+ Summary: Common Python functions for time handling
5
+ Author-email: Corne Bester <corne.bester@gmail.com>
6
+ License-Expression: MIT
7
+ License-File: LICENSE
8
+ Dynamic: license-file
@@ -0,0 +1,11 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ src/python_time_functions.egg-info/PKG-INFO
5
+ src/python_time_functions.egg-info/SOURCES.txt
6
+ src/python_time_functions.egg-info/dependency_links.txt
7
+ src/python_time_functions.egg-info/top_level.txt
8
+ src/time_fuctions_cornebester/__init__.py
9
+ src/time_fuctions_cornebester/time_functions.py
10
+ tests/test_time_function_sanitizer.py
11
+ tests/test_time_functions.py
@@ -0,0 +1 @@
1
+ time_fuctions_cornebester
@@ -0,0 +1,296 @@
1
+ """
2
+ ################################################################################
3
+ # time_functions #
4
+ # #
5
+ # Description: #
6
+ # Frequently used python time conversions #
7
+ # #
8
+ # Author: #
9
+ # Corne Bester <corne.bester@gmail.com> #
10
+ # #
11
+ # This program is free software: you can redistribute it and/or modify #
12
+ # it under the terms of the GNU General Public License as published by #
13
+ # the Free Software Foundation, either version 2 of the License, or #
14
+ # (at your option) any later version. #
15
+ # #
16
+ # This program is distributed in the hope that it will be useful, #
17
+ # but WITHOUT ANY WARRANTY; without even the implied warranty of #
18
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
19
+ # GNU General Public License for more details. #
20
+ # #
21
+ # You should have received a copy of the GNU General Public License #
22
+ # along with this program. If not, see <https://www.gnu.org/licenses/>. #
23
+ ################################################################################
24
+
25
+ """
26
+
27
+ import logging
28
+ from datetime import datetime, timezone
29
+
30
+ logger = logging.getLogger(__name__)
31
+
32
+
33
+ def get_timestamp_iso8601_millis(datetime_obj):
34
+ """
35
+ Take a UTC datetime object as input. E.g.:
36
+
37
+ obj = datetime.now(timezone.utc)
38
+
39
+ Returns an UTC ISO8601 formatted timestamp with milliseconds from passed datetime object
40
+
41
+ https://stackoverflow.com/questions/10286204/what-is-the-right-json-date-format
42
+ """
43
+ utc_iso = datetime_obj.replace(tzinfo=None).isoformat(timespec="milliseconds") + "Z"
44
+ return utc_iso
45
+
46
+
47
+ def get_timestamp_iso8601_micros(datetime_obj):
48
+ """
49
+ Take a UTC datetime object as input. E.g.:
50
+
51
+ obj = datetime.now(timezone.utc)
52
+
53
+ Returns an UTC ISO8601 formatted timestamp with microseconds from passed datetime object
54
+
55
+ https://stackoverflow.com/questions/10286204/what-is-the-right-json-date-format
56
+ """
57
+ utc_iso = datetime_obj.replace(tzinfo=None).isoformat() + "Z"
58
+ return utc_iso
59
+
60
+
61
+ def get_timestamp_iso8601(datetime_obj):
62
+ """
63
+ Take a UTC datetime object as input. E.g.:
64
+
65
+ obj = datetime.now(timezone.utc)
66
+
67
+ Returns an UTC ISO8601 formatted timestamp with seconds from passed datetime object
68
+
69
+ https://stackoverflow.com/questions/10286204/what-is-the-right-json-date-format
70
+ """
71
+ utc_iso = datetime_obj.replace(tzinfo=None).isoformat(timespec="seconds") + "Z"
72
+ return utc_iso
73
+
74
+
75
+ def get_timestamp_unix(datetime_obj):
76
+ """
77
+ Returns an UTC timestamp as a seconds float with sub seconds as the decimal values
78
+ """
79
+ if datetime_obj.tzname() == "UTC":
80
+ utc_unix_time = (
81
+ datetime_obj.timestamp()
82
+ ) # object to seconds float type with subseconds as decimal value
83
+ return int(utc_unix_time)
84
+ elif datetime_obj.tzname() is None:
85
+ utc_unix_time = datetime_obj.replace(
86
+ tzinfo=timezone.utc
87
+ ).timestamp() # object to seconds float type with subseconds as decimal value
88
+ return int(utc_unix_time)
89
+ else:
90
+ raise ValueError("Unexpected value, not supported")
91
+
92
+
93
+ def get_timestamp_unix_subseconds_decimal(datetime_obj):
94
+ """
95
+ Returns an UTC timestamp as a seconds float with sub seconds as the decimal value
96
+ """
97
+ if datetime_obj.tzname() == "UTC":
98
+ utc_unix_time = (
99
+ datetime_obj.timestamp()
100
+ ) # object to seconds float type with subseconds as decimal value
101
+ return utc_unix_time
102
+ elif datetime_obj.tzname() is None:
103
+ utc_unix_time = datetime_obj.replace(
104
+ tzinfo=timezone.utc
105
+ ).timestamp() # object to seconds float type with subseconds as decimal value
106
+ return utc_unix_time
107
+ else:
108
+ raise ValueError("Unexpected value, not supported")
109
+
110
+
111
+ def get_timestamp_unix_millis(datetime_obj):
112
+ """
113
+ Returns an UTC timestamp integer as milliseconds
114
+ """
115
+ if datetime_obj.tzname() == "UTC":
116
+ utc_unix_time = (
117
+ datetime_obj.timestamp()
118
+ ) # object to seconds float type with subseconds as decimal value
119
+ utc_unix_time_millis = utc_unix_time * 1e3 # milliseconds
120
+ return int(utc_unix_time_millis)
121
+ elif datetime_obj.tzname() is None:
122
+ utc_unix_time = datetime_obj.replace(
123
+ tzinfo=timezone.utc
124
+ ).timestamp() # object to seconds float type with subseconds as decimal value
125
+ utc_unix_time_millis = utc_unix_time * 1e3 # milliseconds
126
+ return int(utc_unix_time_millis)
127
+ else:
128
+ raise ValueError("Unexpected value, not supported")
129
+
130
+
131
+ def get_timestamp_unix_micros(datetime_obj):
132
+ """
133
+ Returns an UTC timestamp integer as microseconds
134
+ """
135
+ if datetime_obj.tzname() == "UTC":
136
+ utc_unix_time = (
137
+ datetime_obj.timestamp()
138
+ ) # object to seconds float type with subseconds as decimal value
139
+ utc_unix_time_micros = utc_unix_time * 1e6 # microseconds
140
+ return int(utc_unix_time_micros)
141
+ elif datetime_obj.tzname() is None:
142
+ utc_unix_time = datetime_obj.replace(
143
+ tzinfo=timezone.utc
144
+ ).timestamp() # object to seconds float type with subseconds as decimal value
145
+ utc_unix_time_micros = utc_unix_time * 1e6 # microseconds
146
+ return int(utc_unix_time_micros)
147
+ else:
148
+ raise ValueError("Unexpected value, not supported")
149
+
150
+
151
+ def convert_iso_string_to_datetime_obj(iso_string):
152
+ """
153
+ Returns a datetime obj from an ISO 8601 timestamp with Zulu /UTC suffix
154
+ """
155
+ remove_zulu = iso_string.removesuffix("Z")
156
+ datetime_obj = datetime.fromisoformat(remove_zulu) # string to obj
157
+ datetime_obj_to_utc = datetime_obj.replace(tzinfo=timezone.utc)
158
+ return datetime_obj_to_utc
159
+
160
+
161
+ def convert_unix_to_datetime_obj(utc_unix_time_var):
162
+ """
163
+ Returns a datetime obj from unix timestamp.
164
+ accept:
165
+ int of seconds, milliseconds or microseconds
166
+ float of seconds with subseconds millis or micros
167
+ e.g. 1739738432.888289 OR 1739738432.888 OR 1739738432
168
+ """
169
+ try:
170
+ if isinstance(utc_unix_time_var, int):
171
+ if len(str(utc_unix_time_var)) == 10:
172
+ datetime_obj = datetime.fromtimestamp(
173
+ utc_unix_time_var, tz=timezone.utc
174
+ ) # to obj
175
+ return datetime_obj
176
+ elif len(str(utc_unix_time_var)) == 13:
177
+ datetime_obj = datetime.fromtimestamp(
178
+ utc_unix_time_var / 1000, tz=timezone.utc
179
+ ) # to obj
180
+ return datetime_obj
181
+ elif len(str(utc_unix_time_var)) == 16:
182
+ datetime_obj = datetime.fromtimestamp(
183
+ utc_unix_time_var / 1000000, tz=timezone.utc
184
+ ) # to obj
185
+ return datetime_obj
186
+ else:
187
+ logger.warning("incorrect length. Must be 10, 13 or 16 digits")
188
+ elif isinstance(utc_unix_time_var, float):
189
+ datetime_obj = datetime.fromtimestamp(
190
+ utc_unix_time_var, tz=timezone.utc
191
+ ) # to obj
192
+ return datetime_obj
193
+ except Exception as e2:
194
+ logger.exception(e2)
195
+
196
+
197
+ def timestamp_parser_psql_millis(timestamp):
198
+ """
199
+ * Function to convert common timestamps for use with postgresql query with millisecond precision.
200
+ * Strips higher precision.
201
+ * does not fix/sanitize bad formats
202
+ Accept inputs:
203
+ * ISO8601/rfc3399 in second, millisecond or microsecond precision
204
+ * int Unix time (epoch) in seconds, milliseconds and microseconds
205
+ * float Unix time (epoch) in seconds with milliseconds and microseconds as decimal. e.g. 1742742625.002908
206
+ """
207
+ if isinstance(timestamp, int):
208
+ if len(str(timestamp)) == 10:
209
+ return timestamp
210
+ elif len(str(timestamp)) == 13:
211
+ timestamp = timestamp / 1000
212
+ return timestamp
213
+ elif len(str(timestamp)) == 16:
214
+ timestamp = str(timestamp / 1000000)[:14]
215
+ return float(timestamp)
216
+ elif isinstance(timestamp, float):
217
+ decimal_index = str.index(str(timestamp), ".")
218
+ if decimal_index == 10:
219
+ timestamp = str(timestamp)[:14] # remove microsecond precision
220
+ return float(timestamp)
221
+ else:
222
+ logger.error("Non-standard format {timestamp}")
223
+ elif isinstance(timestamp, str):
224
+ if len(timestamp) == 20:
225
+ obj_from_iso = convert_iso_string_to_datetime_obj(timestamp)
226
+ unix_with_subseconds = get_timestamp_unix_subseconds_decimal(obj_from_iso)
227
+ timestamp = unix_with_subseconds
228
+ return timestamp
229
+ if len(timestamp) == 24:
230
+ obj_from_iso = convert_iso_string_to_datetime_obj(timestamp)
231
+ unix_with_subseconds = get_timestamp_unix_subseconds_decimal(obj_from_iso)
232
+ timestamp = unix_with_subseconds
233
+ return timestamp
234
+ elif len(timestamp) == 27:
235
+ obj_from_iso = convert_iso_string_to_datetime_obj(timestamp)
236
+ unix_with_subseconds = get_timestamp_unix_subseconds_decimal(obj_from_iso)
237
+ timestamp = str(unix_with_subseconds)[:14]
238
+ return float(timestamp)
239
+
240
+
241
+ def timestamp_sanitizer_psql(input):
242
+ '''
243
+ Normalize unix timestamps to postgresl friendly float with millisecond decimals. 14 digits
244
+ Attemps to fix/sanitize bad timestamps
245
+ handle timestamnp as:
246
+ unix micros or millis in decimal format
247
+ unix millis or micros in unix format
248
+ iso8601
249
+ '''
250
+ try:
251
+ if isinstance(input, int):
252
+ if len(str(input)) == 10:
253
+ logger.debug("Not millsecond precision: %s", input)
254
+ return input
255
+ elif len(str(input)) == 13:
256
+ normalized = str((input/1000))[:14]
257
+ logger.debug("Normalizing timestamp for postgresql from %s to %s", input, normalized)
258
+ return float(normalized)
259
+ elif len(str(input)) == 16:
260
+ normalized = str(input/1000000)[:14]
261
+ logger.debug("Normalizing timestamp for postgresql from %s to %s", input, normalized)
262
+ return float(normalized)
263
+ elif isinstance(input, float):
264
+ # elif '.' in str(input):
265
+ decimal_index = str.index(str(input), '.')
266
+ if decimal_index == 13:
267
+ normalized = str(input/1000)[:14] # remove microsecond precision
268
+ logger.debug("Normalizing timestamp for postgresql from %s to %s", input, normalized)
269
+ return float(normalized)
270
+ elif decimal_index == 10:
271
+ normalized = str(input)[:14] # remove microsecond precision
272
+ logger.debug("Normalizing timestamp for postgresql from %s to %s", input, normalized)
273
+ return float(normalized)
274
+ elif isinstance(input, str):
275
+ if len(input) == 20:
276
+ obj_from_iso = convert_iso_string_to_datetime_obj(input)
277
+ unix_with_subseconds = get_timestamp_unix_subseconds_decimal(obj_from_iso)
278
+ normalized = unix_with_subseconds
279
+ logger.debug("Normalizing timestamp for postgresql from %s to %s", input, normalized)
280
+ return float(normalized)
281
+ if len(input) == 24:
282
+ obj_from_iso = convert_iso_string_to_datetime_obj(input)
283
+ unix_with_subseconds = get_timestamp_unix_subseconds_decimal(obj_from_iso)
284
+ normalized = unix_with_subseconds
285
+ logger.debug("Normalizing timestamp for postgresql from %s to %s", input, normalized)
286
+ return float(normalized)
287
+ elif len(input) == 27:
288
+ obj_from_iso = convert_iso_string_to_datetime_obj(input)
289
+ unix_with_subseconds = get_timestamp_unix_subseconds_decimal(obj_from_iso)
290
+ normalized = str(unix_with_subseconds)[:14]
291
+ logger.debug("Normalizing timestamp for postgresql from %s to %s", input, normalized)
292
+ return float(normalized)
293
+ else:
294
+ logger.error("Unexcpected timestamp format")
295
+ except Exception as msg:
296
+ logger.exception(msg)
@@ -0,0 +1,64 @@
1
+ import src.time_fuctions_cornebester.time_functions as time_functions
2
+
3
+ def test_convertions_from_sample23():
4
+ assert float(time_functions.timestamp_sanitizer_psql(1742758997)) == 1742758997
5
+
6
+
7
+ def test_convertions_from_sample24():
8
+ '''
9
+ # unix seconds
10
+ '''
11
+ assert int(time_functions.timestamp_sanitizer_psql(1742758997)) == 1742758997
12
+
13
+
14
+ def test_convertions_from_sample25():
15
+ '''
16
+ # unix millis
17
+ '''
18
+ assert float(time_functions.timestamp_sanitizer_psql(1742758997018)) == 1742758997.018
19
+
20
+
21
+ def test_convertions_from_sample26():
22
+ '''
23
+ # unix micros
24
+ '''
25
+ assert float(time_functions.timestamp_sanitizer_psql(1742758997018308)) == 1742758997.018
26
+
27
+
28
+ def test_convertions_from_sample27():
29
+ '''
30
+ # unix micros
31
+ '''
32
+ assert float(time_functions.timestamp_sanitizer_psql(1742758997018308)) == 1742758997.018
33
+
34
+
35
+ def test_convertions_from_sample28():
36
+ '''
37
+ # psql special
38
+ '''
39
+ assert float(time_functions.timestamp_sanitizer_psql(1742758997.018308)) == 1742758997.018
40
+
41
+
42
+ def test_convertions_from_sample29():
43
+ '''
44
+ # psql special
45
+ '''
46
+ assert float(time_functions.timestamp_sanitizer_psql(1742758997.018)) == 1742758997.018
47
+
48
+
49
+ def test_convertions_from_sample30():
50
+ '''
51
+ # bad format
52
+ '''
53
+ assert float(time_functions.timestamp_sanitizer_psql(1742758997018.308)) == 1742758997.018
54
+
55
+
56
+ def test_convertions_from_sample31():
57
+ '''
58
+ # bad format
59
+ '''
60
+ assert float(time_functions.timestamp_sanitizer_psql("2025-03-23T19:43:17.018Z")) == 1742758997.018
61
+
62
+
63
+ def test_convertions_from_sample32():
64
+ assert time_functions.timestamp_sanitizer_psql(1742742625002.908) == 1742742625.002
@@ -0,0 +1,180 @@
1
+ import logging
2
+ from datetime import datetime, timezone
3
+ import src.time_fuctions_cornebester.time_functions as time_functions
4
+
5
+
6
+ new_obj = datetime.now(timezone.utc)
7
+
8
+ iso = time_functions.get_timestamp_iso8601(new_obj)
9
+ iso_millis = time_functions.get_timestamp_iso8601_millis(new_obj)
10
+ iso_micros = time_functions.get_timestamp_iso8601_micros(new_obj)
11
+
12
+
13
+ unix = time_functions.get_timestamp_unix(new_obj)
14
+ unix_millis = time_functions.get_timestamp_unix_millis(new_obj)
15
+ unix_micros = time_functions.get_timestamp_unix_micros(new_obj)
16
+ unix_with_subseconds = time_functions.get_timestamp_unix_subseconds_decimal(new_obj)
17
+
18
+
19
+ obj_from_iso = time_functions.convert_iso_string_to_datetime_obj(iso)
20
+ obj_from_iso_millis = time_functions.convert_iso_string_to_datetime_obj(iso_millis)
21
+ obj_from_iso_micros = time_functions.convert_iso_string_to_datetime_obj(iso_micros)
22
+
23
+ obj_from_unix_seconds = time_functions.convert_unix_to_datetime_obj(unix)
24
+ obj_from_unix_milliseconds = time_functions.convert_unix_to_datetime_obj(unix_millis)
25
+ obj_from_unix_microseconds = time_functions.convert_unix_to_datetime_obj(unix_micros)
26
+
27
+ obj_from_unix_seconds_float_millis = time_functions.convert_unix_to_datetime_obj(unix_millis/1000)
28
+ obj_from_unix_seconds_float_micros = time_functions.convert_unix_to_datetime_obj(unix_micros/1000000)
29
+ obj_from_unix_seconds_float = time_functions.convert_unix_to_datetime_obj(unix_with_subseconds)
30
+
31
+
32
+ def test_convertions_from_sample():
33
+ assert time_functions.convert_unix_to_datetime_obj(1742736574) == time_functions.convert_iso_string_to_datetime_obj("2025-03-23T13:29:34+00:00")
34
+
35
+
36
+ def test_convertions_from_sample2():
37
+ assert time_functions.convert_unix_to_datetime_obj(1742737159020) == time_functions.convert_iso_string_to_datetime_obj("2025-03-23T13:39:19.020Z")
38
+
39
+
40
+ def test_convertions_from_sample3():
41
+ assert time_functions.convert_unix_to_datetime_obj(1742737771434946) == time_functions.convert_iso_string_to_datetime_obj("2025-03-23T13:49:31.434946Z")
42
+
43
+
44
+ def test_convertions_from_sample4():
45
+ assert time_functions.convert_unix_to_datetime_obj(unix) == time_functions.convert_iso_string_to_datetime_obj(iso)
46
+
47
+
48
+ def test_convertions_from_sample5():
49
+ assert time_functions.convert_unix_to_datetime_obj(unix_millis) == time_functions.convert_iso_string_to_datetime_obj(iso_millis)
50
+
51
+
52
+ def test_convertions_from_sample6():
53
+ assert time_functions.convert_unix_to_datetime_obj(unix_micros) == time_functions.convert_iso_string_to_datetime_obj(iso_micros)
54
+
55
+
56
+ def test_convertions_from_sample7():
57
+ assert obj_from_iso == obj_from_unix_seconds
58
+
59
+
60
+ def test_convertions_from_sample8():
61
+ assert obj_from_iso_millis == obj_from_unix_milliseconds
62
+
63
+
64
+ def test_convertions_from_sample9():
65
+ assert obj_from_iso_micros == obj_from_unix_microseconds
66
+
67
+
68
+ def test_convertions_from_sample10():
69
+ assert obj_from_iso_millis == obj_from_unix_seconds_float_millis
70
+
71
+
72
+ def test_convertions_from_sample11():
73
+ assert obj_from_iso_micros == obj_from_unix_seconds_float_micros
74
+
75
+
76
+ def test_convertions_from_sample12():
77
+ assert obj_from_iso_micros == obj_from_unix_seconds_float
78
+
79
+
80
+ def test_convertions_from_sample13():
81
+ assert time_functions.convert_unix_to_datetime_obj(unix_with_subseconds) == time_functions.convert_iso_string_to_datetime_obj(iso_micros)
82
+
83
+
84
+ def test_convertions_from_sample14():
85
+ '''
86
+ # obj_from_iso = time_functions.convert_iso_string_to_datetime_obj("2025-03-23T15:10:25Z")
87
+ # unix_with_subseconds = int(time_functions.get_timestamp_unix_subseconds_decimal(obj_from_iso))
88
+ # unix_with_subseconds == 1742742625
89
+ '''
90
+ assert time_functions.timestamp_parser_psql_millis("2025-03-23T15:10:25Z") == 1742742625
91
+
92
+
93
+ def test_convertions_from_sample15():
94
+ '''
95
+ # obj_from_iso = time_functions.convert_iso_string_to_datetime_obj("2025-03-23T15:10:25.002Z")
96
+ # unix_with_subseconds = time_functions.get_timestamp_unix_subseconds_decimal(obj_from_iso)
97
+ # unix_with_subseconds == 1742742625.002
98
+ '''
99
+ assert time_functions.timestamp_parser_psql_millis("2025-03-23T15:10:25.002Z") == 1742742625.002
100
+
101
+
102
+ def test_convertions_from_sample16():
103
+ '''
104
+ # obj_from_iso = time_functions.convert_iso_string_to_datetime_obj("2025-03-23T15:10:25.002908Z")
105
+ # unix_with_subseconds = time_functions.get_timestamp_unix_subseconds_decimal(obj_from_iso)
106
+ # unix_with_subseconds == 1742742625.002908
107
+ '''
108
+ assert time_functions.timestamp_parser_psql_millis("2025-03-23T15:10:25.002908Z") == 1742742625.002
109
+
110
+
111
+ def test_convertions_from_sample17():
112
+ assert time_functions.timestamp_parser_psql_millis(1742742625) == 1742742625
113
+
114
+
115
+ def test_convertions_from_sample18():
116
+ '''
117
+ postgresql timeformat
118
+ '''
119
+ assert time_functions.timestamp_parser_psql_millis(1742742625.0) == 1742742625.0
120
+
121
+
122
+ def test_convertions_from_sample19():
123
+ '''
124
+ postgresql timeformat
125
+ '''
126
+ assert time_functions.timestamp_parser_psql_millis(1742742625.002) == 1742742625.002
127
+
128
+
129
+ def test_convertions_from_sample20():
130
+ '''
131
+ postgresql timeformat
132
+ '''
133
+ assert time_functions.timestamp_parser_psql_millis(1742742625.002908) == 1742742625.002
134
+
135
+
136
+ def test_convertions_from_sample21():
137
+ '''
138
+ python millis timeformat
139
+ '''
140
+ assert time_functions.timestamp_parser_psql_millis(1742742625002) == 1742742625.002
141
+
142
+
143
+ def test_convertions_from_sample22():
144
+ '''
145
+ python micros timeformat
146
+ '''
147
+ assert time_functions.timestamp_parser_psql_millis(1742742625002908) == 1742742625.002
148
+
149
+ def test_convertions_from_sample33():
150
+ '''
151
+ postgresql nano timeformat
152
+ '''
153
+ assert time_functions.timestamp_parser_psql_millis(1742742625.002908123) == 1742742625.002
154
+
155
+
156
+ def test_convertions_from_sample32():
157
+ '''
158
+ bad timeformat
159
+ '''
160
+ assert time_functions.timestamp_parser_psql_millis(1742742625002.908) is None
161
+
162
+
163
+ def test_convertions_from_sample34():
164
+ '''
165
+ bad timeformat
166
+ '''
167
+ assert time_functions.timestamp_sanitizer_psql(1729755232184) == 1729755232.184
168
+
169
+ def test_convertions_from_sample35():
170
+ '''
171
+ bad timeformat
172
+ '''
173
+ assert time_functions.timestamp_sanitizer_psql(1729765227856.3) == 1729765227.856
174
+
175
+
176
+ def test_convertions_from_sample36():
177
+ '''
178
+ bad timeformat
179
+ '''
180
+ assert time_functions.timestamp_sanitizer_psql(1729765228327.051) == 1729765228.327