-
-
Notifications
You must be signed in to change notification settings - Fork 18.4k
/
Copy pathnp_datetime_strings.c
1547 lines (1396 loc) · 41.6 KB
/
np_datetime_strings.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* This file implements string parsing and creation for NumPy datetime.
*
* Written by Mark Wiebe ([email protected])
* Copyright (c) 2011 by Enthought, Inc.
*
* See NP_LICENSE.txt for the license.
*/
#define PY_SSIZE_T_CLEAN
#define NO_IMPORT
#include <Python.h>
#include <time.h>
#include <numpy/arrayobject.h>
#include "numpy/arrayscalars.h"
#include "np_datetime.h"
#include "np_datetime_strings.h"
NPY_NO_EXPORT const char *
npy_casting_to_string(NPY_CASTING casting)
{
switch (casting) {
case NPY_NO_CASTING:
return "'no'";
case NPY_EQUIV_CASTING:
return "'equiv'";
case NPY_SAFE_CASTING:
return "'safe'";
case NPY_SAME_KIND_CASTING:
return "'same_kind'";
case NPY_UNSAFE_CASTING:
return "'unsafe'";
default:
return "<unknown>";
}
}
/* Platform-specific time_t typedef */
typedef time_t NPY_TIME_T;
/*// We *do* want these symbols, but for cython, not for C. fine in mac osx,*/
/*// linux complains.*/
/*static void _suppress_unused_variable_warning(void)*/
/*{*/
/* int x = days_per_month_table[0][0];*/
/* x = x;*/
/* int y = _month_offset[0][0];*/
/* y = y;*/
/* char *z = _datetime_strings[0];*/
/* z = z;*/
/*}*/
/* Exported as DATETIMEUNITS in multiarraymodule.c */
static char *_datetime_strings[PANDAS_DATETIME_NUMUNITS] = {
"Y",
"M",
"W",
"D",
"h",
"m",
"s",
"ms",
"us",
"ns",
"ps",
"fs",
"as",
};
/*
* Wraps `localtime` functionality for multiple platforms. This
* converts a time value to a time structure in the local timezone.
*
* Returns 0 on success, -1 on failure.
*/
static int
get_localtime(NPY_TIME_T *ts, struct tm *tms)
{
char *func_name = "<unknown>";
#if defined(_WIN32)
#if defined(_MSC_VER) && (_MSC_VER >= 1400)
if (localtime_s(tms, ts) != 0) {
func_name = "localtime_s";
goto fail;
}
#elif defined(__GNUC__) && defined(NPY_MINGW_USE_CUSTOM_MSVCR)
if (_localtime64_s(tms, ts) != 0) {
func_name = "_localtime64_s";
goto fail;
}
#else
struct tm *tms_tmp;
tms_tmp = localtime(ts);
if (tms_tmp == NULL) {
func_name = "localtime";
goto fail;
}
memcpy(tms, tms_tmp, sizeof(struct tm));
#endif
#else
if (localtime_r(ts, tms) == NULL) {
func_name = "localtime_r";
goto fail;
}
#endif
return 0;
fail:
PyErr_Format(PyExc_OSError, "Failed to use '%s' to convert "
"to a local time", func_name);
return -1;
}
#if 0
/*
* Wraps `gmtime` functionality for multiple platforms. This
* converts a time value to a time structure in UTC.
*
* Returns 0 on success, -1 on failure.
*/
static int
get_gmtime(NPY_TIME_T *ts, struct tm *tms)
{
char *func_name = "<unknown>";
#if defined(_WIN32)
#if defined(_MSC_VER) && (_MSC_VER >= 1400)
if (gmtime_s(tms, ts) != 0) {
func_name = "gmtime_s";
goto fail;
}
#elif defined(__GNUC__) && defined(NPY_MINGW_USE_CUSTOM_MSVCR)
if (_gmtime64_s(tms, ts) != 0) {
func_name = "_gmtime64_s";
goto fail;
}
#else
struct tm *tms_tmp;
tms_tmp = gmtime(ts);
if (tms_tmp == NULL) {
func_name = "gmtime";
goto fail;
}
memcpy(tms, tms_tmp, sizeof(struct tm));
#endif
#else
if (gmtime_r(ts, tms) == NULL) {
func_name = "gmtime_r";
goto fail;
}
#endif
return 0;
fail:
PyErr_Format(PyExc_OSError, "Failed to use '%s' to convert "
"to a UTC time", func_name);
return -1;
}
#endif
/*
* Converts a datetimestruct in UTC to a datetimestruct in local time,
* also returning the timezone offset applied.
*
* Returns 0 on success, -1 on failure.
*/
static int
convert_datetimestruct_utc_to_local(pandas_datetimestruct *out_dts_local,
const pandas_datetimestruct *dts_utc, int *out_timezone_offset)
{
NPY_TIME_T rawtime = 0, localrawtime;
struct tm tm_;
npy_int64 year_correction = 0;
/* Make a copy of the input 'dts' to modify */
*out_dts_local = *dts_utc;
/* HACK: Use a year < 2038 for later years for small time_t */
if (sizeof(NPY_TIME_T) == 4 && out_dts_local->year >= 2038) {
if (is_leapyear(out_dts_local->year)) {
/* 2036 is a leap year */
year_correction = out_dts_local->year - 2036;
out_dts_local->year -= year_correction;
}
else {
/* 2037 is not a leap year */
year_correction = out_dts_local->year - 2037;
out_dts_local->year -= year_correction;
}
}
/*
* Convert everything in 'dts' to a time_t, to minutes precision.
* This is POSIX time, which skips leap-seconds, but because
* we drop the seconds value from the pandas_datetimestruct, everything
* is ok for this operation.
*/
rawtime = (time_t)get_datetimestruct_days(out_dts_local) * 24 * 60 * 60;
rawtime += dts_utc->hour * 60 * 60;
rawtime += dts_utc->min * 60;
/* localtime converts a 'time_t' into a local 'struct tm' */
if (get_localtime(&rawtime, &tm_) < 0) {
return -1;
}
/* Copy back all the values except seconds */
out_dts_local->min = tm_.tm_min;
out_dts_local->hour = tm_.tm_hour;
out_dts_local->day = tm_.tm_mday;
out_dts_local->month = tm_.tm_mon + 1;
out_dts_local->year = tm_.tm_year + 1900;
/* Extract the timezone offset that was applied */
rawtime /= 60;
localrawtime = (time_t)get_datetimestruct_days(out_dts_local) * 24 * 60;
localrawtime += out_dts_local->hour * 60;
localrawtime += out_dts_local->min;
*out_timezone_offset = localrawtime - rawtime;
/* Reapply the year 2038 year correction HACK */
out_dts_local->year += year_correction;
return 0;
}
#if 0
/*
* Converts a datetimestruct in local time to a datetimestruct in UTC.
*
* Returns 0 on success, -1 on failure.
*/
static int
convert_datetimestruct_local_to_utc(pandas_datetimestruct *out_dts_utc,
const pandas_datetimestruct *dts_local)
{
npy_int64 year_correction = 0;
/* Make a copy of the input 'dts' to modify */
*out_dts_utc = *dts_local;
/* HACK: Use a year < 2038 for later years for small time_t */
if (sizeof(NPY_TIME_T) == 4 && out_dts_utc->year >= 2038) {
if (is_leapyear(out_dts_utc->year)) {
/* 2036 is a leap year */
year_correction = out_dts_utc->year - 2036;
out_dts_utc->year -= year_correction;
}
else {
/* 2037 is not a leap year */
year_correction = out_dts_utc->year - 2037;
out_dts_utc->year -= year_correction;
}
}
/*
* ISO 8601 states to treat date-times without a timezone offset
* or 'Z' for UTC as local time. The C standard libary functions
* mktime and gmtime allow us to do this conversion.
*
* Only do this timezone adjustment for recent and future years.
* In this case, "recent" is defined to be 1970 and later, because
* on MS Windows, mktime raises an error when given an earlier date.
*/
if (out_dts_utc->year >= 1970) {
NPY_TIME_T rawtime = 0;
struct tm tm_;
tm_.tm_sec = out_dts_utc->sec;
tm_.tm_min = out_dts_utc->min;
tm_.tm_hour = out_dts_utc->hour;
tm_.tm_mday = out_dts_utc->day;
tm_.tm_mon = out_dts_utc->month - 1;
tm_.tm_year = out_dts_utc->year - 1900;
tm_.tm_isdst = -1;
/* mktime converts a local 'struct tm' into a time_t */
rawtime = mktime(&tm_);
if (rawtime == -1) {
PyErr_SetString(PyExc_OSError, "Failed to use mktime to "
"convert local time to UTC");
return -1;
}
/* gmtime converts a 'time_t' into a UTC 'struct tm' */
if (get_gmtime(&rawtime, &tm_) < 0) {
return -1;
}
out_dts_utc->sec = tm_.tm_sec;
out_dts_utc->min = tm_.tm_min;
out_dts_utc->hour = tm_.tm_hour;
out_dts_utc->day = tm_.tm_mday;
out_dts_utc->month = tm_.tm_mon + 1;
out_dts_utc->year = tm_.tm_year + 1900;
}
/* Reapply the year 2038 year correction HACK */
out_dts_utc->year += year_correction;
return 0;
}
#endif
/* int */
/* parse_python_string(PyObject* obj, pandas_datetimestruct *dts) { */
/* PyObject *bytes = NULL; */
/* char *str = NULL; */
/* Py_ssize_t len = 0; */
/* PANDAS_DATETIMEUNIT bestunit = -1; */
/* /\* Convert to an ASCII string for the date parser *\/ */
/* if (PyUnicode_Check(obj)) { */
/* bytes = PyUnicode_AsASCIIString(obj); */
/* if (bytes == NULL) { */
/* return -1; */
/* } */
/* } */
/* else { */
/* bytes = obj; */
/* Py_INCREF(bytes); */
/* } */
/* if (PyBytes_AsStringAndSize(bytes, &str, &len) == -1) { */
/* Py_DECREF(bytes); */
/* return -1; */
/* } */
/* /\* Parse the ISO date *\/ */
/* if (parse_iso_8601_datetime(str, len, PANDAS_FR_us, NPY_UNSAFE_CASTING, */
/* dts, NULL, &bestunit, NULL) < 0) { */
/* Py_DECREF(bytes); */
/* return -1; */
/* } */
/* Py_DECREF(bytes); */
/* return 0; */
/* } */
/*
* Parses (almost) standard ISO 8601 date strings. The differences are:
*
* + Only seconds may have a decimal point, with up to 18 digits after it
* (maximum attoseconds precision).
* + Either a 'T' as in ISO 8601 or a ' ' may be used to separate
* the date and the time. Both are treated equivalently.
* + Doesn't (yet) handle the "YYYY-DDD" or "YYYY-Www" formats.
* + Doesn't handle leap seconds (seconds value has 60 in these cases).
* + Doesn't handle 24:00:00 as synonym for midnight (00:00:00) tomorrow
* + Accepts special values "NaT" (not a time), "Today", (current
* day according to local time) and "Now" (current time in UTC).
* + ':' separator between hours, minutes, and seconds is optional. When
* omitted, each component must be 2 digits if it appears. (GH-10041)
*
* 'str' must be a NULL-terminated string, and 'len' must be its length.
* 'unit' should contain -1 if the unit is unknown, or the unit
* which will be used if it is.
* 'casting' controls how the detected unit from the string is allowed
* to be cast to the 'unit' parameter.
*
* 'out' gets filled with the parsed date-time.
* 'out_local' gets set to 1 if the parsed time contains timezone,
* to 0 otherwise.
* 'out_tzoffset' gets set to timezone offset by minutes
* if the parsed time was in local time,
* to 0 otherwise. The values 'now' and 'today' don't get counted
* as local, and neither do UTC +/-#### timezone offsets, because
* they aren't using the computer's local timezone offset.
* 'out_bestunit' gives a suggested unit based on the amount of
* resolution provided in the string, or -1 for NaT.
* 'out_special' gets set to 1 if the parsed time was 'today',
* 'now', or ''/'NaT'. For 'today', the unit recommended is
* 'D', for 'now', the unit recommended is 's', and for 'NaT'
* the unit recommended is 'Y'.
*
* Returns 0 on success, -1 on failure.
*/
int
parse_iso_8601_datetime(char *str, int len,
PANDAS_DATETIMEUNIT unit,
NPY_CASTING casting,
pandas_datetimestruct *out,
int *out_local,
int *out_tzoffset,
PANDAS_DATETIMEUNIT *out_bestunit,
npy_bool *out_special)
{
int year_leap = 0;
int i, numdigits;
char *substr, sublen;
PANDAS_DATETIMEUNIT bestunit;
/* If year-month-day are separated by a valid separator,
* months/days without leading zeroes will be parsed
* (though not iso8601). If the components aren't separated,
* 4 (YYYY) or 8 (YYYYMMDD) digits are expected. 6 digits are
* forbidden here (but parsed as YYMMDD elsewhere).
*/
int has_ymd_sep = 0;
char ymd_sep = '\0';
char valid_ymd_sep[] = {'-', '.', '/', '\\', ' '};
int valid_ymd_sep_len = sizeof(valid_ymd_sep);
/* hour-minute-second may or may not separated by ':'. If not, then
* each component must be 2 digits. */
int has_hms_sep = 0;
int hour_was_2_digits = 0;
/* Initialize the output to all zeros */
memset(out, 0, sizeof(pandas_datetimestruct));
out->month = 1;
out->day = 1;
/*
* The string "today" means take today's date in local time, and
* convert it to a date representation. This date representation, if
* forced into a time unit, will be at midnight UTC.
* This is perhaps a little weird, but done so that the
* 'datetime64[D]' type produces the date you expect, rather than
* switching to an adjacent day depending on the current time and your
* timezone.
*/
if (len == 5 && tolower(str[0]) == 't' &&
tolower(str[1]) == 'o' &&
tolower(str[2]) == 'd' &&
tolower(str[3]) == 'a' &&
tolower(str[4]) == 'y') {
NPY_TIME_T rawtime = 0;
struct tm tm_;
time(&rawtime);
if (get_localtime(&rawtime, &tm_) < 0) {
return -1;
}
out->year = tm_.tm_year + 1900;
out->month = tm_.tm_mon + 1;
out->day = tm_.tm_mday;
bestunit = PANDAS_FR_D;
/*
* Indicate that this was a special value, and
* is a date (unit 'D').
*/
if (out_local != NULL) {
*out_local = 0;
}
if (out_bestunit != NULL) {
*out_bestunit = bestunit;
}
if (out_special != NULL) {
*out_special = 1;
}
/* Check the casting rule */
if (unit != -1 && !can_cast_datetime64_units(bestunit, unit,
casting)) {
PyErr_Format(PyExc_TypeError, "Cannot parse \"%s\" as unit "
"'%s' using casting rule %s",
str, _datetime_strings[unit],
npy_casting_to_string(casting));
return -1;
}
return 0;
}
/* The string "now" resolves to the current UTC time */
if (len == 3 && tolower(str[0]) == 'n' &&
tolower(str[1]) == 'o' &&
tolower(str[2]) == 'w') {
NPY_TIME_T rawtime = 0;
pandas_datetime_metadata meta;
time(&rawtime);
/* Set up a dummy metadata for the conversion */
meta.base = PANDAS_FR_s;
meta.num = 1;
bestunit = PANDAS_FR_s;
/*
* Indicate that this was a special value, and
* use 's' because the time() function has resolution
* seconds.
*/
if (out_local != NULL) {
*out_local = 0;
}
if (out_bestunit != NULL) {
*out_bestunit = bestunit;
}
if (out_special != NULL) {
*out_special = 1;
}
/* Check the casting rule */
if (unit != -1 && !can_cast_datetime64_units(bestunit, unit,
casting)) {
PyErr_Format(PyExc_TypeError, "Cannot parse \"%s\" as unit "
"'%s' using casting rule %s",
str, _datetime_strings[unit],
npy_casting_to_string(casting));
return -1;
}
return convert_datetime_to_datetimestruct(&meta, rawtime, out);
}
/* Anything else isn't a special value */
if (out_special != NULL) {
*out_special = 0;
}
substr = str;
sublen = len;
/* Skip leading whitespace */
while (sublen > 0 && isspace(*substr)) {
++substr;
--sublen;
}
/* Leading '-' sign for negative year */
if (*substr == '-') {
++substr;
--sublen;
}
if (sublen == 0) {
goto parse_error;
}
/* PARSE THE YEAR (4 digits) */
out->year = 0;
if (sublen >= 4 && isdigit(substr[0]) && isdigit(substr[1]) &&
isdigit(substr[2]) && isdigit(substr[3])) {
out->year = 1000 * (substr[0] - '0') + 100 * (substr[1] - '0') +
10 * (substr[2] - '0') + (substr[3] - '0');
substr += 4;
sublen -= 4;;
}
/* Negate the year if necessary */
if (str[0] == '-') {
out->year = -out->year;
}
/* Check whether it's a leap-year */
year_leap = is_leapyear(out->year);
/* Next character must be a separator, start of month, or end of string */
if (sublen == 0) {
if (out_local != NULL) {
*out_local = 0;
}
bestunit = PANDAS_FR_Y;
goto finish;
}
if (!isdigit(*substr)) {
for (i = 0; i < valid_ymd_sep_len; ++i) {
if (*substr == valid_ymd_sep[i]) {
break;
}
}
if (i == valid_ymd_sep_len) {
goto parse_error;
}
has_ymd_sep = 1;
ymd_sep = valid_ymd_sep[i];
++substr;
--sublen;
/* Cannot have trailing separator */
if (sublen == 0 || !isdigit(*substr)) {
goto parse_error;
}
}
/* PARSE THE MONTH */
/* First digit required */
out->month = (*substr - '0');
++substr;
--sublen;
/* Second digit optional if there was a separator */
if (isdigit(*substr)) {
out->month = 10 * out->month + (*substr - '0');
++substr;
--sublen;
}
else if (!has_ymd_sep) {
goto parse_error;
}
if (out->month < 1 || out->month > 12) {
PyErr_Format(PyExc_ValueError,
"Month out of range in datetime string \"%s\"", str);
goto error;
}
/* Next character must be the separator, start of day, or end of string */
if (sublen == 0) {
/* Forbid YYYYMM. Parsed instead as YYMMDD by someone else. */
if (!has_ymd_sep) {
goto parse_error;
}
if (out_local != NULL) {
*out_local = 0;
}
bestunit = PANDAS_FR_M;
goto finish;
}
if (has_ymd_sep) {
/* Must have separator, but cannot be trailing */
if (*substr != ymd_sep || sublen == 1) {
goto parse_error;
}
++substr;
--sublen;
}
/* PARSE THE DAY */
/* First digit required */
if (!isdigit(*substr)) {
goto parse_error;
}
out->day = (*substr - '0');
++substr;
--sublen;
/* Second digit optional if there was a separator */
if (isdigit(*substr)) {
out->day = 10 * out->day + (*substr - '0');
++substr;
--sublen;
}
else if (!has_ymd_sep) {
goto parse_error;
}
if (out->day < 1 ||
out->day > days_per_month_table[year_leap][out->month-1])
{
PyErr_Format(PyExc_ValueError,
"Day out of range in datetime string \"%s\"", str);
goto error;
}
/* Next character must be a 'T', ' ', or end of string */
if (sublen == 0) {
if (out_local != NULL) {
*out_local = 0;
}
bestunit = PANDAS_FR_D;
goto finish;
}
if ((*substr != 'T' && *substr != ' ') || sublen == 1) {
goto parse_error;
}
++substr;
--sublen;
/* PARSE THE HOURS */
/* First digit required */
if (!isdigit(*substr)) {
goto parse_error;
}
out->hour = (*substr - '0');
++substr;
--sublen;
/* Second digit optional */
if (isdigit(*substr)) {
hour_was_2_digits = 1;
out->hour = 10 * out->hour + (*substr - '0');
++substr;
--sublen;
if (out->hour >= 24) {
PyErr_Format(PyExc_ValueError,
"Hours out of range in datetime string \"%s\"", str);
goto error;
}
}
/* Next character must be a ':' or the end of the string */
if (sublen == 0) {
if (!hour_was_2_digits) {
goto parse_error;
}
bestunit = PANDAS_FR_h;
goto finish;
}
if (*substr == ':') {
has_hms_sep = 1;
++substr;
--sublen;
/* Cannot have a trailing separator */
if (sublen == 0 || !isdigit(*substr)) {
goto parse_error;
}
}
else if (!isdigit(*substr)) {
if (!hour_was_2_digits) {
goto parse_error;
}
bestunit = PANDAS_FR_h;
goto parse_timezone;
}
/* PARSE THE MINUTES */
/* First digit required */
out->min = (*substr - '0');
++substr;
--sublen;
/* Second digit optional if there was a separator */
if (isdigit(*substr)) {
out->min = 10 * out->min + (*substr - '0');
++substr;
--sublen;
if (out->min >= 60) {
PyErr_Format(PyExc_ValueError,
"Minutes out of range in datetime string \"%s\"", str);
goto error;
}
}
else if (!has_hms_sep) {
goto parse_error;
}
if (sublen == 0) {
bestunit = PANDAS_FR_m;
goto finish;
}
/* If we make it through this condition block, then the next
* character is a digit. */
if (has_hms_sep && *substr == ':') {
++substr;
--sublen;
/* Cannot have a trailing ':' */
if (sublen == 0 || !isdigit(*substr)) {
goto parse_error;
}
}
else if (!has_hms_sep && isdigit(*substr)) {
}
else {
bestunit = PANDAS_FR_m;
goto parse_timezone;
}
/* PARSE THE SECONDS */
/* First digit required */
out->sec = (*substr - '0');
++substr;
--sublen;
/* Second digit optional if there was a separator */
if (isdigit(*substr)) {
out->sec = 10 * out->sec + (*substr - '0');
++substr;
--sublen;
if (out->sec >= 60) {
PyErr_Format(PyExc_ValueError,
"Seconds out of range in datetime string \"%s\"", str);
goto error;
}
}
else if (!has_hms_sep) {
goto parse_error;
}
/* Next character may be a '.' indicating fractional seconds */
if (sublen > 0 && *substr == '.') {
++substr;
--sublen;
}
else {
bestunit = PANDAS_FR_s;
goto parse_timezone;
}
/* PARSE THE MICROSECONDS (0 to 6 digits) */
numdigits = 0;
for (i = 0; i < 6; ++i) {
out->us *= 10;
if (sublen > 0 && isdigit(*substr)) {
out->us += (*substr - '0');
++substr;
--sublen;
++numdigits;
}
}
if (sublen == 0 || !isdigit(*substr)) {
if (numdigits > 3) {
bestunit = PANDAS_FR_us;
}
else {
bestunit = PANDAS_FR_ms;
}
goto parse_timezone;
}
/* PARSE THE PICOSECONDS (0 to 6 digits) */
numdigits = 0;
for (i = 0; i < 6; ++i) {
out->ps *= 10;
if (sublen > 0 && isdigit(*substr)) {
out->ps += (*substr - '0');
++substr;
--sublen;
++numdigits;
}
}
if (sublen == 0 || !isdigit(*substr)) {
if (numdigits > 3) {
bestunit = PANDAS_FR_ps;
}
else {
bestunit = PANDAS_FR_ns;
}
goto parse_timezone;
}
/* PARSE THE ATTOSECONDS (0 to 6 digits) */
numdigits = 0;
for (i = 0; i < 6; ++i) {
out->as *= 10;
if (sublen > 0 && isdigit(*substr)) {
out->as += (*substr - '0');
++substr;
--sublen;
++numdigits;
}
}
if (numdigits > 3) {
bestunit = PANDAS_FR_as;
}
else {
bestunit = PANDAS_FR_fs;
}
parse_timezone:
/* trim any whitepsace between time/timeezone */
while (sublen > 0 && isspace(*substr)) {
++substr;
--sublen;
}
if (sublen == 0) {
// Unlike NumPy, treating no time zone as naive
goto finish;
}
/* UTC specifier */
if (*substr == 'Z') {
/* "Z" should be equivalent to tz offset "+00:00" */
if (out_local != NULL) {
*out_local = 1;
}
if (out_tzoffset != NULL) {
*out_tzoffset = 0;
}
if (sublen == 1) {
goto finish;
}
else {
++substr;
--sublen;
}
}
/* Time zone offset */
else if (*substr == '-' || *substr == '+') {
int offset_neg = 0, offset_hour = 0, offset_minute = 0;
/*
* Since "local" means local with respect to the current
* machine, we say this is non-local.
*/
if (*substr == '-') {
offset_neg = 1;
}
++substr;
--sublen;
/* The hours offset */
if (sublen >= 2 && isdigit(substr[0]) && isdigit(substr[1])) {
offset_hour = 10 * (substr[0] - '0') + (substr[1] - '0');
substr += 2;
sublen -= 2;
if (offset_hour >= 24) {
PyErr_Format(PyExc_ValueError,
"Timezone hours offset out of range "
"in datetime string \"%s\"", str);
goto error;
}
}
else if (sublen >= 1 && isdigit(substr[0])) {
offset_hour = substr[0] - '0';
++substr;
--sublen;
}
else {
goto parse_error;
}
/* The minutes offset is optional */
if (sublen > 0) {
/* Optional ':' */
if (*substr == ':') {
++substr;
--sublen;
}
/* The minutes offset (at the end of the string) */
if (sublen >= 2 && isdigit(substr[0]) && isdigit(substr[1])) {
offset_minute = 10 * (substr[0] - '0') + (substr[1] - '0');
substr += 2;
sublen -= 2;
if (offset_minute >= 60) {
PyErr_Format(PyExc_ValueError,
"Timezone minutes offset out of range "
"in datetime string \"%s\"", str);
goto error;
}
}
else if (sublen >= 1 && isdigit(substr[0])) {
offset_minute = substr[0] - '0';
++substr;
--sublen;
}
else {
goto parse_error;
}
}
/* Apply the time zone offset */
if (offset_neg) {
offset_hour = -offset_hour;
offset_minute = -offset_minute;
}
if (out_local != NULL) {
*out_local = 1;
// Unlike NumPy, do not change internal value to local time
*out_tzoffset = 60 * offset_hour + offset_minute;
}
}
/* Skip trailing whitespace */
while (sublen > 0 && isspace(*substr)) {
++substr;
--sublen;
}
if (sublen != 0) {
goto parse_error;
}
finish:
if (out_bestunit != NULL) {
*out_bestunit = bestunit;
}
/* Check the casting rule */
if (unit != -1 && !can_cast_datetime64_units(bestunit, unit,
casting)) {
PyErr_Format(PyExc_TypeError, "Cannot parse \"%s\" as unit "
"'%s' using casting rule %s",
str, _datetime_strings[unit],
npy_casting_to_string(casting));
return -1;
}
return 0;
parse_error:
PyErr_Format(PyExc_ValueError,
"Error parsing datetime string \"%s\" at position %d",
str, (int)(substr-str));
return -1;
error:
return -1;
}
/*
* Provides a string length to use for converting datetime