@@ -236,3 +236,61 @@ def timestamp_parser_psql_millis(timestamp):
236236 unix_with_subseconds = get_timestamp_unix_subseconds_decimal (obj_from_iso )
237237 timestamp = str (unix_with_subseconds )[:14 ]
238238 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 commit comments