FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
cpython/Modules/_datetimemodule.c at pythoncapi · pythoncapi/cpython · GitHub
cpython/Modules/_datetimemodule.c at pythoncapi · pythoncapi/cpython · GitHub
Skip to content
Navigation Menu
Sign in
Appearance settings
AI CODE CREATION
GitHub Copilot
Write better code with AI
GitHub Copilot app
Direct agents from issue to merge
MCP Registry
Integrate external tools
DEVELOPER WORKFLOWS
Actions
Automate any workflow
Codespaces
Instant dev environments
Issues
Plan and track work
Code Review
Manage code changes
Code Quality
Enforce quality at merge
APPLICATION SECURITY
GitHub Advanced Security
Find and fix vulnerabilities
Code security
Secure your code as you build
Secret protection
Stop leaks before they start
EXPLORE
Why GitHub
Documentation
Blog
Changelog
Marketplace
View all features
BY COMPANY SIZE
Enterprises
Small and medium teams
Startups
Nonprofits
BY USE CASE
App Modernization
DevSecOps
DevOps
CI/CD
View all use cases
BY INDUSTRY
Healthcare
Financial services
Manufacturing
Government
View all industries
View all solutions
EXPLORE BY TOPIC
AI
Software Development
DevOps
Security
View all topics
EXPLORE BY TYPE
Customer stories
Events & webinars
Ebooks & reports
Business insights
GitHub Skills
SUPPORT & SERVICES
Documentation
Customer support
Community forum
Trust center
Partners
View all resources
COMMUNITY
GitHub Sponsors
Fund open source developers
PROGRAMS
Security Lab
Maintainer Community
GitHub Stars
Archive Program
REPOSITORIES
Topics
Trending
Collections
ENTERPRISE SOLUTIONS
Enterprise platform
AI-powered developer platform
AVAILABLE ADD-ONS
GitHub Advanced Security
Enterprise-grade security features
Copilot for Business
Enterprise-grade AI features
Premium Support
Enterprise-grade 24/7 support
Pricing
Sign in
Sign up
Appearance settings
You signed in with another tab or window.
Reload
to refresh your session.
You signed out in another tab or window.
Reload
to refresh your session.
You switched accounts on another tab or window.
Reload
to refresh your session.
Dismiss alert
{{ message }}
Uh oh!
There was an error while loading.
Please reload this page
.
pythoncapi
/
cpython
Public
forked from
python/cpython
Notifications
You must be signed in to change notification settings
Fork
0
Star
1
Code
Pull requests
0
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
cpython
/
Modules
/
_datetimemodule.c
Copy path
More file actions
More file actions
Latest commit
History
History
History
6644 lines (5789 loc) · 208 KB
Breadcrumbs
cpython
/
Modules
/
_datetimemodule.c
Copy path
File metadata and controls
6644 lines (5789 loc) · 208 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
/* C implementation for the date/time type documented at
* http://www.zope.org/Members/fdrake/DateTimeWiki/FrontPage
*/
#include
"Python.h"
#include
"structmember.h"
#include
<time.h>
#ifdef
MS_WINDOWS
# include
<winsock2.h>
/* struct timeval */
#endif
/* Differentiate between building the core module and building extension
* modules.
*/
#ifndef
Py_BUILD_CORE
#define
Py_BUILD_CORE
#endif
#include
"datetime.h"
#undef
Py_BUILD_CORE
/*[clinic input]
module datetime
class datetime.datetime "PyDateTime_DateTime *" "&PyDateTime_DateTimeType"
[clinic start generated code]*/
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=78142cb64b9e98bc]*/
#include
"clinic/_datetimemodule.c.h"
/* We require that C int be at least 32 bits, and use int virtually
* everywhere. In just a few cases we use a temp long, where a Python
* API returns a C long. In such cases, we have to ensure that the
* final result fits in a C int (this can be an issue on 64-bit boxes).
*/
#if
SIZEOF_INT
<
4
# error
"_datetime.c requires that C int have at least 32 bits"
#endif
#define
MINYEAR
1
#define
MAXYEAR
9999
#define
MAXORDINAL
3652059
/* date(9999,12,31).toordinal() */
/* Nine decimal digits is easy to communicate, and leaves enough room
* so that two delta days can be added w/o fear of overflowing a signed
* 32-bit int, and with plenty of room left over to absorb any possible
* carries from adding seconds.
*/
#define
MAX_DELTA_DAYS
999999999
/* Rename the long macros in datetime.h to more reasonable short names. */
#define
GET_YEAR
PyDateTime_GET_YEAR
#define
GET_MONTH
PyDateTime_GET_MONTH
#define
GET_DAY
PyDateTime_GET_DAY
#define
DATE_GET_HOUR
PyDateTime_DATE_GET_HOUR
#define
DATE_GET_MINUTE
PyDateTime_DATE_GET_MINUTE
#define
DATE_GET_SECOND
PyDateTime_DATE_GET_SECOND
#define
DATE_GET_MICROSECOND
PyDateTime_DATE_GET_MICROSECOND
#define
DATE_GET_FOLD
PyDateTime_DATE_GET_FOLD
/* Date accessors for date and datetime. */
#define
SET_YEAR
(
o
,
v
) (((o)->data[0] = ((v) & 0xff00) >> 8), \
((o)->data[1] = ((v) & 0x00ff)))
#define
SET_MONTH
(
o
,
v
) (PyDateTime_GET_MONTH(o) = (v))
#define
SET_DAY
(
o
,
v
) (PyDateTime_GET_DAY(o) = (v))
/* Date/Time accessors for datetime. */
#define
DATE_SET_HOUR
(
o
,
v
) (PyDateTime_DATE_GET_HOUR(o) = (v))
#define
DATE_SET_MINUTE
(
o
,
v
) (PyDateTime_DATE_GET_MINUTE(o) = (v))
#define
DATE_SET_SECOND
(
o
,
v
) (PyDateTime_DATE_GET_SECOND(o) = (v))
#define
DATE_SET_MICROSECOND
(
o
,
v
) \
(((o)->data[7] = ((v) & 0xff0000) >> 16), \
((o)->data[8] = ((v) & 0x00ff00) >> 8), \
((o)->data[9] = ((v) & 0x0000ff)))
#define
DATE_SET_FOLD
(
o
,
v
) (PyDateTime_DATE_GET_FOLD(o) = (v))
/* Time accessors for time. */
#define
TIME_GET_HOUR
PyDateTime_TIME_GET_HOUR
#define
TIME_GET_MINUTE
PyDateTime_TIME_GET_MINUTE
#define
TIME_GET_SECOND
PyDateTime_TIME_GET_SECOND
#define
TIME_GET_MICROSECOND
PyDateTime_TIME_GET_MICROSECOND
#define
TIME_GET_FOLD
PyDateTime_TIME_GET_FOLD
#define
TIME_SET_HOUR
(
o
,
v
) (PyDateTime_TIME_GET_HOUR(o) = (v))
#define
TIME_SET_MINUTE
(
o
,
v
) (PyDateTime_TIME_GET_MINUTE(o) = (v))
#define
TIME_SET_SECOND
(
o
,
v
) (PyDateTime_TIME_GET_SECOND(o) = (v))
#define
TIME_SET_MICROSECOND
(
o
,
v
) \
(((o)->data[3] = ((v) & 0xff0000) >> 16), \
((o)->data[4] = ((v) & 0x00ff00) >> 8), \
((o)->data[5] = ((v) & 0x0000ff)))
#define
TIME_SET_FOLD
(
o
,
v
) (PyDateTime_TIME_GET_FOLD(o) = (v))
/* Delta accessors for timedelta. */
#define
GET_TD_DAYS
(
o
) (((PyDateTime_Delta *)(o))->days)
#define
GET_TD_SECONDS
(
o
) (((PyDateTime_Delta *)(o))->seconds)
#define
GET_TD_MICROSECONDS
(
o
) (((PyDateTime_Delta *)(o))->microseconds)
#define
SET_TD_DAYS
(
o
,
v
) ((o)->days = (v))
#define
SET_TD_SECONDS
(
o
,
v
) ((o)->seconds = (v))
#define
SET_TD_MICROSECONDS
(
o
,
v
) ((o)->microseconds = (v))
/* p is a pointer to a time or a datetime object; HASTZINFO(p) returns
* p->hastzinfo.
*/
#define
HASTZINFO
(
p
) (((_PyDateTime_BaseTZInfo *)(p))->hastzinfo)
#define
GET_TIME_TZINFO
(
p
) (HASTZINFO(p) ? \
((PyDateTime_Time *)(p))->tzinfo : Py_None)
#define
GET_DT_TZINFO
(
p
) (HASTZINFO(p) ? \
((PyDateTime_DateTime *)(p))->tzinfo : Py_None)
/* M is a char or int claiming to be a valid month. The macro is equivalent
* to the two-sided Python test
* 1 <= M <= 12
*/
#define
MONTH_IS_SANE
(
M
) ((unsigned int)(M) - 1 < 12)
/* Forward declarations. */
static
PyTypeObject
PyDateTime_DateType
;
static
PyTypeObject
PyDateTime_DateTimeType
;
static
PyTypeObject
PyDateTime_DeltaType
;
static
PyTypeObject
PyDateTime_TimeType
;
static
PyTypeObject
PyDateTime_TZInfoType
;
static
PyTypeObject
PyDateTime_TimeZoneType
;
static
int
check_tzinfo_subclass
(
PyObject
*
p
);
_Py_IDENTIFIER
(
as_integer_ratio
);
_Py_IDENTIFIER
(
fromutc
);
_Py_IDENTIFIER
(
isoformat
);
_Py_IDENTIFIER
(
strftime
);
/* ---------------------------------------------------------------------------
* Math utilities.
*/
/* k = i+j overflows iff k differs in sign from both inputs,
* iff k^i has sign bit set and k^j has sign bit set,
* iff (k^i)&(k^j) has sign bit set.
*/
#define
SIGNED_ADD_OVERFLOWED
(
RESULT
,
I
,
J
) \
((((RESULT) ^ (I)) & ((RESULT) ^ (J))) < 0)
/* Compute Python divmod(x, y), returning the quotient and storing the
* remainder into *r. The quotient is the floor of x/y, and that's
* the real point of this. C will probably truncate instead (C99
* requires truncation; C89 left it implementation-defined).
* Simplification: we *require* that y > 0 here. That's appropriate
* for all the uses made of it. This simplifies the code and makes
* the overflow case impossible (divmod(LONG_MIN, -1) is the only
* overflow case).
*/
static
int
divmod
(
int
x
,
int
y
,
int
*
r
)
{
int
quo
;
assert
(
y
>
0
);
quo
=
x
/
y
;
*
r
=
x
-
quo
*
y
;
if
(
*
r
<
0
) {
--
quo
;
*
r
+=
y
;
}
assert
(
0
<=
*
r
&&
*
r
<
y
);
return
quo
;
}
/* Nearest integer to m / n for integers m and n. Half-integer results
* are rounded to even.
*/
static
PyObject
*
divide_nearest
(
PyObject
*
m
,
PyObject
*
n
)
{
PyObject
*
result
;
PyObject
*
temp
;
temp
=
_PyLong_DivmodNear
(
m
,
n
);
if
(
temp
==
NULL
)
return
NULL
;
result
=
PyTuple_GetItemRef
(
temp
,
0
);
Py_DECREF
(
temp
);
return
result
;
}
/* ---------------------------------------------------------------------------
* General calendrical helper functions
*/
/* For each month ordinal in 1..12, the number of days in that month,
* and the number of days before that month in the same year. These
* are correct for non-leap years only.
*/
static
const
int
_days_in_month
[]
=
{
0
,
/* unused; this vector uses 1-based indexing */
31
,
28
,
31
,
30
,
31
,
30
,
31
,
31
,
30
,
31
,
30
,
31
};
static
const
int
_days_before_month
[]
=
{
0
,
/* unused; this vector uses 1-based indexing */
0
,
31
,
59
,
90
,
120
,
151
,
181
,
212
,
243
,
273
,
304
,
334
};
/* year -> 1 if leap year, else 0. */
static
int
is_leap
(
int
year
)
{
/* Cast year to unsigned. The result is the same either way, but
* C can generate faster code for unsigned mod than for signed
* mod (especially for % 4 -- a good compiler should just grab
* the last 2 bits when the LHS is unsigned).
*/
const
unsigned
int
ayear
=
(
unsigned
int
)
year
;
return
ayear
%
4
==
0
&&
(
ayear
%
100
!=
0
||
ayear
%
400
==
0
);
}
/* year, month -> number of days in that month in that year */
static
int
days_in_month
(
int
year
,
int
month
)
{
assert
(
month
>=
1
);
assert
(
month
<=
12
);
if
(
month
==
2
&&
is_leap
(
year
))
return
29
;
else
return
_days_in_month
[
month
];
}
/* year, month -> number of days in year preceding first day of month */
static
int
days_before_month
(
int
year
,
int
month
)
{
int
days
;
assert
(
month
>=
1
);
assert
(
month
<=
12
);
days
=
_days_before_month
[
month
];
if
(
month
>
2
&&
is_leap
(
year
))
++
days
;
return
days
;
}
/* year -> number of days before January 1st of year. Remember that we
* start with year 1, so days_before_year(1) == 0.
*/
static
int
days_before_year
(
int
year
)
{
int
y
=
year
-
1
;
/* This is incorrect if year <= 0; we really want the floor
* here. But so long as MINYEAR is 1, the smallest year this
* can see is 1.
*/
assert
(
year
>=
1
);
return
y
*
365
+
y
/
4
-
y
/
100
+
y
/
400
;
}
/* Number of days in 4, 100, and 400 year cycles. That these have
* the correct values is asserted in the module init function.
*/
#define
DI4Y
1461
/* days_before_year(5); days in 4 years */
#define
DI100Y
36524
/* days_before_year(101); days in 100 years */
#define
DI400Y
146097
/* days_before_year(401); days in 400 years */
/* ordinal -> year, month, day, considering 01-Jan-0001 as day 1. */
static
void
ord_to_ymd
(
int
ordinal
,
int
*
year
,
int
*
month
,
int
*
day
)
{
int
n
,
n1
,
n4
,
n100
,
n400
,
leapyear
,
preceding
;
/* ordinal is a 1-based index, starting at 1-Jan-1. The pattern of
* leap years repeats exactly every 400 years. The basic strategy is
* to find the closest 400-year boundary at or before ordinal, then
* work with the offset from that boundary to ordinal. Life is much
* clearer if we subtract 1 from ordinal first -- then the values
* of ordinal at 400-year boundaries are exactly those divisible
* by DI400Y:
*
* D M Y n n-1
* -- --- ---- ---------- ----------------
* 31 Dec -400 -DI400Y -DI400Y -1
* 1 Jan -399 -DI400Y +1 -DI400Y 400-year boundary
* ...
* 30 Dec 000 -1 -2
* 31 Dec 000 0 -1
* 1 Jan 001 1 0 400-year boundary
* 2 Jan 001 2 1
* 3 Jan 001 3 2
* ...
* 31 Dec 400 DI400Y DI400Y -1
* 1 Jan 401 DI400Y +1 DI400Y 400-year boundary
*/
assert
(
ordinal
>=
1
);
--
ordinal
;
n400
=
ordinal
/
DI400Y
;
n
=
ordinal
%
DI400Y
;
*
year
=
n400
*
400
+
1
;
/* Now n is the (non-negative) offset, in days, from January 1 of
* year, to the desired date. Now compute how many 100-year cycles
* precede n.
* Note that it's possible for n100 to equal 4! In that case 4 full
* 100-year cycles precede the desired day, which implies the
* desired day is December 31 at the end of a 400-year cycle.
*/
n100
=
n
/
DI100Y
;
n
=
n
%
DI100Y
;
/* Now compute how many 4-year cycles precede it. */
n4
=
n
/
DI4Y
;
n
=
n
%
DI4Y
;
/* And now how many single years. Again n1 can be 4, and again
* meaning that the desired day is December 31 at the end of the
* 4-year cycle.
*/
n1
=
n
/
365
;
n
=
n
%
365
;
*
year
+=
n100
*
100
+
n4
*
4
+
n1
;
if
(
n1
==
4
||
n100
==
4
) {
assert
(
n
==
0
);
*
year
-=
1
;
*
month
=
12
;
*
day
=
31
;
return
;
}
/* Now the year is correct, and n is the offset from January 1. We
* find the month via an estimate that's either exact or one too
* large.
*/
leapyear
=
n1
==
3
&&
(
n4
!=
24
||
n100
==
3
);
assert
(
leapyear
==
is_leap
(
*
year
));
*
month
=
(
n
+
50
) >>
5
;
preceding
=
(
_days_before_month
[
*
month
]
+
(
*
month
>
2
&&
leapyear
));
if
(
preceding
>
n
) {
/* estimate is too large */
*
month
-=
1
;
preceding
-=
days_in_month
(
*
year
,
*
month
);
}
n
-=
preceding
;
assert
(
0
<=
n
);
assert
(
n
<
days_in_month
(
*
year
,
*
month
));
*
day
=
n
+
1
;
}
/* year, month, day -> ordinal, considering 01-Jan-0001 as day 1. */
static
int
ymd_to_ord
(
int
year
,
int
month
,
int
day
)
{
return
days_before_year
(
year
)
+
days_before_month
(
year
,
month
)
+
day
;
}
/* Day of week, where Monday==0, ..., Sunday==6. 1/1/1 was a Monday. */
static
int
weekday
(
int
year
,
int
month
,
int
day
)
{
return
(
ymd_to_ord
(
year
,
month
,
day
)
+
6
) %
7
;
}
/* Ordinal of the Monday starting week 1 of the ISO year. Week 1 is the
* first calendar week containing a Thursday.
*/
static
int
iso_week1_monday
(
int
year
)
{
int
first_day
=
ymd_to_ord
(
year
,
1
,
1
);
/* ord of 1/1 */
/* 0 if 1/1 is a Monday, 1 if a Tue, etc. */
int
first_weekday
=
(
first_day
+
6
) %
7
;
/* ordinal of closest Monday at or before 1/1 */
int
week1_monday
=
first_day
-
first_weekday
;
if
(
first_weekday
>
3
)
/* if 1/1 was Fri, Sat, Sun */
week1_monday
+=
7
;
return
week1_monday
;
}
/* ---------------------------------------------------------------------------
* Range checkers.
*/
/* Check that -MAX_DELTA_DAYS <= days <= MAX_DELTA_DAYS. If so, return 0.
* If not, raise OverflowError and return -1.
*/
static
int
check_delta_day_range
(
int
days
)
{
if
(
-
MAX_DELTA_DAYS
<=
days
&&
days
<=
MAX_DELTA_DAYS
)
return
0
;
PyErr_Format
(
PyExc_OverflowError
,
"days=%d; must have magnitude <= %d"
,
days
,
MAX_DELTA_DAYS
);
return
-1
;
}
/* Check that date arguments are in range. Return 0 if they are. If they
* aren't, raise ValueError and return -1.
*/
static
int
check_date_args
(
int
year
,
int
month
,
int
day
)
{
if
(
year
<
MINYEAR
||
year
>
MAXYEAR
) {
PyErr_Format
(
PyExc_ValueError
,
"year %i is out of range"
,
year
);
return
-1
;
}
if
(
month
<
1
||
month
>
12
) {
PyErr_SetString
(
PyExc_ValueError
,
"month must be in 1..12"
);
return
-1
;
}
if
(
day
<
1
||
day
>
days_in_month
(
year
,
month
)) {
PyErr_SetString
(
PyExc_ValueError
,
"day is out of range for month"
);
return
-1
;
}
return
0
;
}
/* Check that time arguments are in range. Return 0 if they are. If they
* aren't, raise ValueError and return -1.
*/
static
int
check_time_args
(
int
h
,
int
m
,
int
s
,
int
us
,
int
fold
)
{
if
(
h
<
0
||
h
>
23
) {
PyErr_SetString
(
PyExc_ValueError
,
"hour must be in 0..23"
);
return
-1
;
}
if
(
m
<
0
||
m
>
59
) {
PyErr_SetString
(
PyExc_ValueError
,
"minute must be in 0..59"
);
return
-1
;
}
if
(
s
<
0
||
s
>
59
) {
PyErr_SetString
(
PyExc_ValueError
,
"second must be in 0..59"
);
return
-1
;
}
if
(
us
<
0
||
us
>
999999
) {
PyErr_SetString
(
PyExc_ValueError
,
"microsecond must be in 0..999999"
);
return
-1
;
}
if
(
fold
!=
0
&&
fold
!=
1
) {
PyErr_SetString
(
PyExc_ValueError
,
"fold must be either 0 or 1"
);
return
-1
;
}
return
0
;
}
/* ---------------------------------------------------------------------------
* Normalization utilities.
*/
/* One step of a mixed-radix conversion. A "hi" unit is equivalent to
* factor "lo" units. factor must be > 0. If *lo is less than 0, or
* at least factor, enough of *lo is converted into "hi" units so that
* 0 <= *lo < factor. The input values must be such that int overflow
* is impossible.
*/
static
void
normalize_pair
(
int
*
hi
,
int
*
lo
,
int
factor
)
{
assert
(
factor
>
0
);
assert
(
lo
!=
hi
);
if
(
*
lo
<
0
||
*
lo
>=
factor
) {
const
int
num_hi
=
divmod
(
*
lo
,
factor
,
lo
);
const
int
new_hi
=
*
hi
+
num_hi
;
assert
(!
SIGNED_ADD_OVERFLOWED
(
new_hi
,
*
hi
,
num_hi
));
*
hi
=
new_hi
;
}
assert
(
0
<=
*
lo
&&
*
lo
<
factor
);
}
/* Fiddle days (d), seconds (s), and microseconds (us) so that
* 0 <= *s < 24*3600
* 0 <= *us < 1000000
* The input values must be such that the internals don't overflow.
* The way this routine is used, we don't get close.
*/
static
void
normalize_d_s_us
(
int
*
d
,
int
*
s
,
int
*
us
)
{
if
(
*
us
<
0
||
*
us
>=
1000000
) {
normalize_pair
(
s
,
us
,
1000000
);
/* |s| can't be bigger than about
* |original s| + |original us|/1000000 now.
*/
}
if
(
*
s
<
0
||
*
s
>=
24
*
3600
) {
normalize_pair
(
d
,
s
,
24
*
3600
);
/* |d| can't be bigger than about
* |original d| +
* (|original s| + |original us|/1000000) / (24*3600) now.
*/
}
assert
(
0
<=
*
s
&&
*
s
<
24
*
3600
);
assert
(
0
<=
*
us
&&
*
us
<
1000000
);
}
/* Fiddle years (y), months (m), and days (d) so that
* 1 <= *m <= 12
* 1 <= *d <= days_in_month(*y, *m)
* The input values must be such that the internals don't overflow.
* The way this routine is used, we don't get close.
*/
static
int
normalize_y_m_d
(
int
*
y
,
int
*
m
,
int
*
d
)
{
int
dim
;
/* # of days in month */
/* In actual use, m is always the month component extracted from a
* date/datetime object. Therefore it is always in [1, 12] range.
*/
assert
(
1
<=
*
m
&&
*
m
<=
12
);
/* Now only day can be out of bounds (year may also be out of bounds
* for a datetime object, but we don't care about that here).
* If day is out of bounds, what to do is arguable, but at least the
* method here is principled and explainable.
*/
dim
=
days_in_month
(
*
y
,
*
m
);
if
(
*
d
<
1
||
*
d
>
dim
) {
/* Move day-1 days from the first of the month. First try to
* get off cheap if we're only one day out of range
* (adjustments for timezone alone can't be worse than that).
*/
if
(
*
d
==
0
) {
--
*
m
;
if
(
*
m
>
0
)
*
d
=
days_in_month
(
*
y
,
*
m
);
else
{
--
*
y
;
*
m
=
12
;
*
d
=
31
;
}
}
else
if
(
*
d
==
dim
+
1
) {
/* move forward a day */
++
*
m
;
*
d
=
1
;
if
(
*
m
>
12
) {
*
m
=
1
;
++
*
y
;
}
}
else
{
int
ordinal
=
ymd_to_ord
(
*
y
,
*
m
,
1
)
+
*
d
-
1
;
if
(
ordinal
<
1
||
ordinal
>
MAXORDINAL
) {
goto
error
;
}
else
{
ord_to_ymd
(
ordinal
,
y
,
m
,
d
);
return
0
;
}
}
}
assert
(
*
m
>
0
);
assert
(
*
d
>
0
);
if
(
MINYEAR
<=
*
y
&&
*
y
<=
MAXYEAR
)
return
0
;
error
:
PyErr_SetString
(
PyExc_OverflowError
,
"date value out of range"
);
return
-1
;
}
/* Fiddle out-of-bounds months and days so that the result makes some kind
* of sense. The parameters are both inputs and outputs. Returns < 0 on
* failure, where failure means the adjusted year is out of bounds.
*/
static
int
normalize_date
(
int
*
year
,
int
*
month
,
int
*
day
)
{
return
normalize_y_m_d
(
year
,
month
,
day
);
}
/* Force all the datetime fields into range. The parameters are both
* inputs and outputs. Returns < 0 on error.
*/
static
int
normalize_datetime
(
int
*
year
,
int
*
month
,
int
*
day
,
int
*
hour
,
int
*
minute
,
int
*
second
,
int
*
microsecond
)
{
normalize_pair
(
second
,
microsecond
,
1000000
);
normalize_pair
(
minute
,
second
,
60
);
normalize_pair
(
hour
,
minute
,
60
);
normalize_pair
(
day
,
hour
,
24
);
return
normalize_date
(
year
,
month
,
day
);
}
/* ---------------------------------------------------------------------------
* Basic object allocation: tp_alloc implementations. These allocate
* Python objects of the right size and type, and do the Python object-
* initialization bit. If there's not enough memory, they return NULL after
* setting MemoryError. All data members remain uninitialized trash.
*
* We abuse the tp_alloc "nitems" argument to communicate whether a tzinfo
* member is needed. This is ugly, imprecise, and possibly insecure.
* tp_basicsize for the time and datetime types is set to the size of the
* struct that has room for the tzinfo member, so subclasses in Python will
* allocate enough space for a tzinfo member whether or not one is actually
* needed. That's the "ugly and imprecise" parts. The "possibly insecure"
* part is that PyType_GenericAlloc() (which subclasses in Python end up
* using) just happens today to effectively ignore the nitems argument
* when tp_itemsize is 0, which it is for these type objects. If that
* changes, perhaps the callers of tp_alloc slots in this file should
* be changed to force a 0 nitems argument unless the type being allocated
* is a base type implemented in this file (so that tp_alloc is time_alloc
* or datetime_alloc below, which know about the nitems abuse).
*/
static
PyObject
*
time_alloc
(
PyTypeObject
*
type
,
Py_ssize_t
aware
)
{
PyObject
*
self
;
self
=
(
PyObject
*
)
PyObject_MALLOC
(
aware
?
sizeof
(
PyDateTime_Time
) :
sizeof
(
_PyDateTime_BaseTime
));
if
(
self
==
NULL
)
return
(
PyObject
*
)
PyErr_NoMemory
();
PyObject_INIT
(
self
,
type
);
return
self
;
}
static
PyObject
*
datetime_alloc
(
PyTypeObject
*
type
,
Py_ssize_t
aware
)
{
PyObject
*
self
;
self
=
(
PyObject
*
)
PyObject_MALLOC
(
aware
?
sizeof
(
PyDateTime_DateTime
) :
sizeof
(
_PyDateTime_BaseDateTime
));
if
(
self
==
NULL
)
return
(
PyObject
*
)
PyErr_NoMemory
();
PyObject_INIT
(
self
,
type
);
return
self
;
}
/* ---------------------------------------------------------------------------
* Helpers for setting object fields. These work on pointers to the
* appropriate base class.
*/
/* For date and datetime. */
static
void
set_date_fields
(
PyDateTime_Date
*
self
,
int
y
,
int
m
,
int
d
)
{
self
->
hashcode
=
-1
;
SET_YEAR
(
self
,
y
);
SET_MONTH
(
self
,
m
);
SET_DAY
(
self
,
d
);
}
/* ---------------------------------------------------------------------------
* String parsing utilities and helper functions
*/
static
const
char
*
parse_digits
(
const
char
*
ptr
,
int
*
var
,
size_t
num_digits
)
{
for
(
size_t
i
=
0
;
i
<
num_digits
;
++
i
) {
unsigned
int
tmp
=
(
unsigned
int
)(
*
(
ptr
++
)
-
'0'
);
if
(
tmp
>
9
) {
return
NULL
;
}
*
var
*=
10
;
*
var
+=
(
signed
int
)
tmp
;
}
return
ptr
;
}
static
int
parse_isoformat_date
(
const
char
*
dtstr
,
int
*
year
,
int
*
month
,
int
*
day
) {
/* Parse the date components of the result of date.isoformat()
*
* Return codes:
* 0: Success
* -1: Failed to parse date component
* -2: Failed to parse dateseparator
*/
const
char
*
p
=
dtstr
;
p
=
parse_digits
(
p
,
year
,
4
);
if
(
NULL
==
p
) {
return
-1
;
}
if
(
*
(
p
++
)
!=
'-'
) {
return
-2
;
}
p
=
parse_digits
(
p
,
month
,
2
);
if
(
NULL
==
p
) {
return
-1
;
}
if
(
*
(
p
++
)
!=
'-'
) {
return
-2
;
}
p
=
parse_digits
(
p
,
day
,
2
);
if
(
p
==
NULL
) {
return
-1
;
}
return
0
;
}
static
int
parse_hh_mm_ss_ff
(
const
char
*
tstr
,
const
char
*
tstr_end
,
int
*
hour
,
int
*
minute
,
int
*
second
,
int
*
microsecond
) {
const
char
*
p
=
tstr
;
const
char
*
p_end
=
tstr_end
;
int
*
vals
[
3
]
=
{
hour
,
minute
,
second
};
// Parse [HH[:MM[:SS]]]
for
(
size_t
i
=
0
;
i
<
3
;
++
i
) {
p
=
parse_digits
(
p
,
vals
[
i
],
2
);
if
(
NULL
==
p
) {
return
-3
;
}
char
c
=
*
(
p
++
);
if
(
p
>=
p_end
) {
return
c
!=
'\0'
;
}
else
if
(
c
==
':'
) {
continue
;
}
else
if
(
c
==
'.'
) {
break
;
}
else
{
return
-4
;
// Malformed time separator
}
}
// Parse .fff[fff]
size_t
len_remains
=
p_end
-
p
;
if
(!(
len_remains
==
6
||
len_remains
==
3
)) {
return
-3
;
}
p
=
parse_digits
(
p
,
microsecond
,
len_remains
);
if
(
NULL
==
p
) {
return
-3
;
}
if
(
len_remains
==
3
) {
*
microsecond
*=
1000
;
}
// Return 1 if it's not the end of the string
return
*
p
!=
'\0'
;
}
static
int
parse_isoformat_time
(
const
char
*
dtstr
,
size_t
dtlen
,
int
*
hour
,
int
*
minute
,
int
*
second
,
int
*
microsecond
,
int
*
tzoffset
,
int
*
tzmicrosecond
) {
// Parse the time portion of a datetime.isoformat() string
//
// Return codes:
// 0: Success (no tzoffset)
// 1: Success (with tzoffset)
// -3: Failed to parse time component
// -4: Failed to parse time separator
// -5: Malformed timezone string
const
char
*
p
=
dtstr
;
const
char
*
p_end
=
dtstr
+
dtlen
;
const
char
*
tzinfo_pos
=
p
;
do
{
if
(
*
tzinfo_pos
==
'+'
||
*
tzinfo_pos
==
'-'
) {
break
;
}
}
while
(
++
tzinfo_pos
<
p_end
);
int
rv
=
parse_hh_mm_ss_ff
(
dtstr
,
tzinfo_pos
,
hour
,
minute
,
second
,
microsecond
);
if
(
rv
<
0
) {
return
rv
;
}
else
if
(
tzinfo_pos
==
p_end
) {
// We know that there's no time zone, so if there's stuff at the
// end of the string it's an error.
if
(
rv
==
1
) {
return
-5
;
}
else
{
return
0
;
}
}
// Parse time zone component
// Valid formats are:
// - +HH:MM (len 6)
// - +HH:MM:SS (len 9)
// - +HH:MM:SS.ffffff (len 16)
size_t
tzlen
=
p_end
-
tzinfo_pos
;
if
(!(
tzlen
==
6
||
tzlen
==
9
||
tzlen
==
16
)) {
return
-5
;
}
int
tzsign
=
(
*
tzinfo_pos
==
'-'
)?
-1
:
1
;
tzinfo_pos
++
;
int
tzhour
=
0
,
tzminute
=
0
,
tzsecond
=
0
;
rv
=
parse_hh_mm_ss_ff
(
tzinfo_pos
,
p_end
,
&
tzhour
,
&
tzminute
,
&
tzsecond
,
tzmicrosecond
);
*
tzoffset
=
tzsign
*
((
tzhour
*
3600
)
+
(
tzminute
*
60
)
+
tzsecond
);
*
tzmicrosecond
*=
tzsign
;
return
rv
?
-5
:
1
;
}
/* ---------------------------------------------------------------------------
* Create various objects, mostly without range checking.
*/
/* Create a date instance with no range checking. */
static
PyObject
*
new_date_ex
(
int
year
,
int
month
,
int
day
,
PyTypeObject
*
type
)
{
PyDateTime_Date
*
self
;
if
(
check_date_args
(
year
,
month
,
day
)
<
0
) {
return
NULL
;
}
self
=
(
PyDateTime_Date
*
) (
type
->
tp_alloc
(
type
,
0
));
if
(
self
!=
NULL
)
set_date_fields
(
self
,
year
,
month
,
day
);
return
(
PyObject
*
)
self
;
}
#define
new_date
(
year
,
month
,
day
) \
new_date_ex(year, month, day, &PyDateTime_DateType)
// Forward declaration
static
PyObject
*
new_datetime_ex
(
int
,
int
,
int
,
int
,
int
,
int
,
int
,
PyObject
*
,
PyTypeObject
*
);
/* Create date instance with no range checking, or call subclass constructor */
static
PyObject
*
new_date_subclass_ex
(
int
year
,
int
month
,
int
day
,
PyObject
*
cls
) {
PyObject
*
result
;
// We have "fast path" constructors for two subclasses: date and datetime
if
((
PyTypeObject
*
)
cls
==
&
PyDateTime_DateType
) {
result
=
new_date_ex
(
year
,
month
,
day
, (
PyTypeObject
*
)
cls
);
}
else
if
((
PyTypeObject
*
)
cls
==
&
PyDateTime_DateTimeType
) {
result
=
new_datetime_ex
(
year
,
month
,
day
,
0
,
0
,
0
,
0
,
Py_None
,
(
PyTypeObject
*
)
cls
);
}
else
{
result
=
PyObject_CallFunction
(
cls
,
"iii"
,
year
,
month
,
day
);
}
return
result
;
}
/* Create a datetime instance with no range checking. */
static
PyObject
*
new_datetime_ex2
(
int
year
,
int
month
,
int
day
,
int
hour
,
int
minute
,
int
second
,
int
usecond
,
PyObject
*
tzinfo
,
int
fold
,
PyTypeObject
*
type
)
{
PyDateTime_DateTime
*
self
;
char
aware
=
tzinfo
!=
Py_None
;
if
(
check_date_args
(
year
,
month
,
day
)
<
0
) {
return
NULL
;
}
if
(
check_time_args
(
hour
,
minute
,
second
,
usecond
,
fold
)
<
0
) {
return
NULL
;
}
if
(
check_tzinfo_subclass
(
tzinfo
)
<
0
) {
return
NULL
;
}
self
=
(
PyDateTime_DateTime
*
) (
type
->
tp_alloc
(
type
,
aware
));
if
(
self
!=
NULL
) {
self
->
hastzinfo
=
aware
;
set_date_fields
((
PyDateTime_Date
*
)
self
,
year
,
month
,
day
);
DATE_SET_HOUR
(
self
,
hour
);
DATE_SET_MINUTE
(
self
,
minute
);
DATE_SET_SECOND
(
self
,
second
);
DATE_SET_MICROSECOND
(
self
,
usecond
);
if
(
aware
) {
Py_INCREF
(
tzinfo
);
self
->
tzinfo
=
tzinfo
;
}
DATE_SET_FOLD
(
self
,
fold
);
}
return
(
PyObject
*
)
self
;
}
static
PyObject
*
new_datetime_ex
(
int
year
,
int
month
,
int
day
,
int
hour
,
int
minute
,
int
second
,
int
usecond
,
PyObject
*
tzinfo
,
PyTypeObject
*
type
)
{
return
new_datetime_ex2
(
year
,
month
,
day
,
hour
,
minute
,
second
,
usecond
,
tzinfo
,
0
,
type
);
}
#define
new_datetime
(
y
,
m
,
d
,
hh
,
mm
,
ss
,
us
,
tzinfo
,
fold
) \
new_datetime_ex2(y, m, d, hh, mm, ss, us, tzinfo, fold, \
&PyDateTime_DateTimeType)
static
PyObject
*
new_datetime_subclass_fold_ex
(
int
year
,
int
month
,
int
day
,
int
hour
,
int
minute
,
int
second
,
int
usecond
,
PyObject
*
tzinfo
,
int
fold
,
PyObject
*
cls
) {
PyObject
*
dt
;
if
((
PyTypeObject
*
)
cls
==
&
PyDateTime_DateTimeType
) {
// Use the fast path constructor
dt
=
new_datetime
(
year
,
month
,
day
,
hour
,
minute
,
second
,
usecond
,
tzinfo
,
fold
);
}
else
{
// Subclass
dt
=
PyObject_CallFunction
(
cls
,
"iiiiiiiO"
,
year
,
month
,
day
,
hour
,
minute
,
second
,
usecond
,
tzinfo
);
}
return
dt
;
}
static
PyObject
*
new_datetime_subclass_ex
(
int
year
,
int
month
,
int
day
,
int
hour
,
int
minute
,
int
second
,
int
usecond
,
PyObject
*
tzinfo
,
PyObject
*
cls
) {
return
new_datetime_subclass_fold_ex
(
year
,
month
,
day
,
hour
,
minute
,
second
,
usecond
,
tzinfo
,
0
,
cls
);
}
/* Create a time instance with no range checking. */
static
PyObject
*
new_time_ex2
(
int
hour
,
int
minute
,
int
second
,
int
usecond
,
PyObject
*
tzinfo
,
int
fold
,
PyTypeObject
*
type
)
{
PyDateTime_Time
*
self
;
char
aware
=
tzinfo
!=
Py_None
;
if
(
check_time_args
(
hour
,
minute
,
second
,
usecond
,
fold
)
<
0
) {
return
NULL
;
}
if
(
check_tzinfo_subclass
(
tzinfo
)
<
0
) {
return
NULL
;
}
self
=
(
PyDateTime_Time
*
) (
type
->
tp_alloc
(
type
,
aware
));
if
(
self
!=
NULL
) {
self
->
hastzinfo
=
aware
;
self
->
hashcode
=
-1
;
TIME_SET_HOUR
(
self
,
hour
);
TIME_SET_MINUTE
(
self
,
minute
);
TIME_SET_SECOND
(
self
,
second
);
TIME_SET_MICROSECOND
(
self
,
usecond
);
if
(
aware
) {
Py_INCREF
(
tzinfo
);
self
->
tzinfo
=
tzinfo
;
}
TIME_SET_FOLD
(
self
,
fold
);
}
return
(
PyObject
*
)
self
;
}
static
PyObject
*
new_time_ex
(
int
hour
,
int
minute
,
int
second
,
int
usecond
,
PyObject
*
tzinfo
,
PyTypeObject
*
type
)
{
return
new_time_ex2
(
hour
,
minute
,
second
,
usecond
,
tzinfo
,
0
,
type
);
}
#define
new_time
(
hh
,
mm
,
ss
,
us
,
tzinfo
,
fold
) \
new_time_ex2(hh, mm, ss, us, tzinfo, fold, &PyDateTime_TimeType)
/* Create a timedelta instance. Normalize the members iff normalize is
* true. Passing false is a speed optimization, if you know for sure
* that seconds and microseconds are already in their proper ranges. In any
* case, raises OverflowError and returns NULL if the normalized days is out
* of range).
*/
static
PyObject
*
new_delta_ex
(
int
days
,
int
seconds
,
int
microseconds
,
int
normalize
,
View remainder of file in raw view
Footer
© 2026 GitHub, Inc.
Footer navigation
Terms
Privacy
Security
Status
Community
Docs
Contact
You can’t perform that action at this time.
Back
|
FazBrowse Home
|
New Git URL