@@ -48,10 +48,7 @@ from numpy cimport (
48
48
)
49
49
50
50
from pandas._libs.missing cimport checknull_with_nat_and_na
51
- from pandas._libs.tslibs.conversion cimport (
52
- convert_timezone,
53
- get_datetime64_nanos,
54
- )
51
+ from pandas._libs.tslibs.conversion cimport get_datetime64_nanos
55
52
from pandas._libs.tslibs.nattype cimport (
56
53
NPY_NAT,
57
54
c_nat_strings as nat_strings,
@@ -73,6 +70,7 @@ import_pandas_datetime()
73
70
from pandas._libs.tslibs.np_datetime import OutOfBoundsDatetime
74
71
75
72
from pandas._libs.tslibs.timestamps cimport _Timestamp
73
+ from pandas._libs.tslibs.timezones cimport tz_compare
76
74
from pandas._libs.util cimport (
77
75
is_float_object,
78
76
is_integer_object,
@@ -156,6 +154,37 @@ cdef dict _parse_code_table = {"y": 0,
156
154
" u" : 22 }
157
155
158
156
157
+ cdef class DatetimeParseState:
158
+ def __cinit__ (self ):
159
+ self .found_tz = False
160
+ self .found_naive = False
161
+
162
+ cdef tzinfo process_datetime(self , datetime dt, tzinfo tz, bint utc_convert):
163
+ if dt.tzinfo is not None :
164
+ self .found_tz = True
165
+ else :
166
+ self .found_naive = True
167
+
168
+ if dt.tzinfo is not None :
169
+ if utc_convert:
170
+ pass
171
+ elif self .found_naive:
172
+ raise ValueError (" Tz-aware datetime.datetime "
173
+ " cannot be converted to "
174
+ " datetime64 unless utc=True" )
175
+ elif tz is not None and not tz_compare(tz, dt.tzinfo):
176
+ raise ValueError (" Tz-aware datetime.datetime "
177
+ " cannot be converted to "
178
+ " datetime64 unless utc=True" )
179
+ else :
180
+ tz = dt.tzinfo
181
+ else :
182
+ if self .found_tz and not utc_convert:
183
+ raise ValueError (" Cannot mix tz-aware with "
184
+ " tz-naive values" )
185
+ return tz
186
+
187
+
159
188
def array_strptime (
160
189
ndarray[object] values ,
161
190
str fmt ,
@@ -183,13 +212,12 @@ def array_strptime(
183
212
bint is_raise = errors== " raise"
184
213
bint is_ignore = errors== " ignore"
185
214
bint is_coerce = errors== " coerce"
186
- bint found_naive = False
187
- bint found_tz = False
188
215
tzinfo tz_out = None
189
216
bint iso_format = format_is_iso(fmt)
190
217
NPY_DATETIMEUNIT out_bestunit
191
218
int out_local = 0 , out_tzoffset = 0
192
219
bint string_to_dts_succeeded = 0
220
+ DatetimeParseState state = DatetimeParseState()
193
221
194
222
assert is_raise or is_ignore or is_coerce
195
223
@@ -276,17 +304,7 @@ def array_strptime(
276
304
iresult[i] = NPY_NAT
277
305
continue
278
306
elif PyDateTime_Check(val):
279
- if val.tzinfo is not None :
280
- found_tz = True
281
- else :
282
- found_naive = True
283
- tz_out = convert_timezone(
284
- val.tzinfo,
285
- tz_out,
286
- found_naive,
287
- found_tz,
288
- utc,
289
- )
307
+ tz_out = state.process_datetime(val, tz_out, utc)
290
308
if isinstance (val, _Timestamp):
291
309
iresult[i] = val.tz_localize(None ).as_unit(" ns" )._value
292
310
else :
0 commit comments