@@ -363,6 +363,27 @@ def setDatetimeTimezone(value):
363363 return DATETIME_TIMEZONE
364364
365365
366+ def _parseTimestamp (value , tzinfo ):
367+ """ Helper function to parse a timestamp value into a datetime object. """
368+ try :
369+ value = int (value )
370+ except ValueError :
371+ log .info ('Failed to parse "%s" to datetime as timestamp, defaulting to None' , value )
372+ return None
373+ try :
374+ if tzinfo :
375+ return datetime .fromtimestamp (value , tz = tzinfo )
376+ return datetime .fromtimestamp (value )
377+ except (OSError , OverflowError , ValueError ):
378+ try :
379+ if tzinfo :
380+ return datetime .fromtimestamp (0 , tz = tzinfo ) + timedelta (seconds = value )
381+ return datetime .fromtimestamp (0 ) + timedelta (seconds = value )
382+ except OverflowError :
383+ log .info ('Failed to parse "%s" to datetime as timestamp (out-of-bounds), defaulting to None' , value )
384+ return None
385+
386+
366387def toDatetime (value , format = None ):
367388 """ Returns a datetime object from the specified value.
368389
@@ -380,23 +401,7 @@ def toDatetime(value, format=None):
380401 log .info ('Failed to parse "%s" to datetime as format "%s", defaulting to None' , value , format )
381402 return None
382403 else :
383- try :
384- value = int (value )
385- except ValueError :
386- log .info ('Failed to parse "%s" to datetime as timestamp, defaulting to None' , value )
387- return None
388- try :
389- if tzinfo :
390- return datetime .fromtimestamp (value , tz = tzinfo )
391- return datetime .fromtimestamp (value )
392- except (OSError , OverflowError , ValueError ):
393- try :
394- if tzinfo :
395- return datetime .fromtimestamp (0 , tz = tzinfo ) + timedelta (seconds = value )
396- return datetime .fromtimestamp (0 ) + timedelta (seconds = value )
397- except OverflowError :
398- log .info ('Failed to parse "%s" to datetime as timestamp (out-of-bounds), defaulting to None' , value )
399- return None
404+ return _parseTimestamp (value , tzinfo )
400405 return value
401406
402407
0 commit comments