Skip to content

Commit c9d9fb2

Browse files
committed
added new helper function - 'setup_tsobject_tz_using_offset'
1 parent cab4df8 commit c9d9fb2

File tree

1 file changed

+28
-24
lines changed

1 file changed

+28
-24
lines changed

pandas/_libs/tslibs/conversion.pyx

+28-24
Original file line numberDiff line numberDiff line change
@@ -393,6 +393,25 @@ cdef _TSObject convert_datetime_to_tsobject(datetime ts, object tz,
393393
return obj
394394

395395

396+
cdef _TSObject setup_tsobject_tz_using_offset(_TSObject obj,
397+
object tz, int tzoffset):
398+
obj.tzinfo = pytz.FixedOffset(tzoffset)
399+
obj.value = tz_convert_single(obj.value, obj.tzinfo, UTC)
400+
if tz is None:
401+
check_overflows(obj)
402+
return obj
403+
else:
404+
# Keep the converter same as PyDateTime's
405+
obj = convert_to_tsobject(obj.value, obj.tzinfo,
406+
None, 0, 0)
407+
dt = datetime(obj.dts.year, obj.dts.month, obj.dts.day,
408+
obj.dts.hour, obj.dts.min, obj.dts.sec,
409+
obj.dts.us, obj.tzinfo)
410+
obj = convert_datetime_to_tsobject(
411+
dt, tz, nanos=obj.dts.ps // 1000)
412+
return obj
413+
414+
396415
cdef _TSObject convert_str_to_tsobject(object ts, object tz, object unit,
397416
bint dayfirst=False,
398417
bint yearfirst=False):
@@ -451,25 +470,11 @@ cdef _TSObject convert_str_to_tsobject(object ts, object tz, object unit,
451470
)
452471
try:
453472
if not string_to_dts_failed:
454-
obj.value = dtstruct_to_dt64(&obj.dts)
455473
check_dts_bounds(&obj.dts)
474+
obj.value = dtstruct_to_dt64(&obj.dts)
456475
if out_local == 1:
457-
obj.tzinfo = pytz.FixedOffset(out_tzoffset)
458-
obj.value = tz_convert_single(obj.value, obj.tzinfo, UTC)
459-
if tz is None:
460-
check_overflows(obj)
461-
return obj
462-
else:
463-
# Keep the converter same as PyDateTime's
464-
obj = convert_to_tsobject(obj.value, obj.tzinfo,
465-
None, 0, 0)
466-
dt = datetime(obj.dts.year, obj.dts.month, obj.dts.day,
467-
obj.dts.hour, obj.dts.min, obj.dts.sec,
468-
obj.dts.us, obj.tzinfo)
469-
obj = convert_datetime_to_tsobject(
470-
dt, tz, nanos=obj.dts.ps // 1000)
471-
return obj
472-
476+
return setup_tsobject_tz_using_offset(obj, tz,
477+
out_tzoffset)
473478
else:
474479
ts = obj.value
475480
if tz is not None:
@@ -486,13 +491,12 @@ cdef _TSObject convert_str_to_tsobject(object ts, object tz, object unit,
486491
except ValueError:
487492
do_parse_datetime_string = True
488493

489-
finally:
490-
if string_to_dts_failed or do_parse_datetime_string:
491-
try:
492-
ts = parse_datetime_string(ts, dayfirst=dayfirst,
493-
yearfirst=yearfirst)
494-
except Exception:
495-
raise ValueError("could not convert string to Timestamp")
494+
if string_to_dts_failed or do_parse_datetime_string:
495+
try:
496+
ts = parse_datetime_string(ts, dayfirst=dayfirst,
497+
yearfirst=yearfirst)
498+
except Exception:
499+
raise ValueError("could not convert string to Timestamp")
496500

497501
return convert_to_tsobject(ts, tz, unit, dayfirst, yearfirst)
498502

0 commit comments

Comments
 (0)