/
datetime.cs
1570 lines (1278 loc) · 63 KB
/
datetime.cs
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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using Microsoft.Scripting;
using Microsoft.Scripting.Runtime;
using Microsoft.Scripting.Utils;
using IronPython.Runtime;
using IronPython.Runtime.Operations;
using IronPython.Runtime.Types;
using System.Numerics;
[assembly: PythonModule("datetime", typeof(IronPython.Modules.PythonDateTime))]
namespace IronPython.Modules {
public class PythonDateTime {
public static readonly int MAXYEAR = DateTime.MaxValue.Year;
public static readonly int MINYEAR = DateTime.MinValue.Year;
public const string __doc__ = "Provides functions and types for working with dates and times.";
[PythonType]
public class timedelta : ICodeFormattable {
internal int _days;
internal int _seconds;
internal int _microseconds;
private TimeSpan _tsWithDaysAndSeconds, _tsWithSeconds; // value type
private bool _fWithDaysAndSeconds = false; // whether _tsWithDaysAndSeconds initialized
private bool _fWithSeconds = false;
internal static readonly timedelta _DayResolution = new timedelta(1, 0, 0);
// class attributes:
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")]
public static readonly timedelta resolution = new timedelta(0, 0, 1);
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")]
public static readonly timedelta min = new timedelta(-MAXDAYS, 0, 0);
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")]
public static readonly timedelta max = new timedelta(MAXDAYS, 86399, 999999);
private const int MAXDAYS = 999999999;
private const double SECONDSPERDAY = 24 * 60 * 60;
internal timedelta(double days, double seconds, double microsecond)
: this(days, seconds, microsecond, 0, 0, 0, 0) {
}
internal timedelta(TimeSpan ts, double microsecond)
: this(ts.Days, ts.Seconds, microsecond, ts.Milliseconds, ts.Minutes, ts.Hours, 0) {
}
public timedelta(double days, double seconds, double microseconds, double milliseconds, double minutes, double hours, double weeks) {
double totalDays = weeks * 7 + days;
double totalSeconds = ((totalDays * 24 + hours) * 60 + minutes) * 60 + seconds;
double totalSecondsSharp = Math.Floor(totalSeconds);
double totalSecondsFloat = totalSeconds - totalSecondsSharp;
double totalMicroseconds = Math.Round(totalSecondsFloat * 1e6 + milliseconds * 1000 + microseconds);
double otherSecondsFromMicroseconds = Math.Floor(totalMicroseconds / 1e6);
totalSecondsSharp += otherSecondsFromMicroseconds;
totalMicroseconds -= otherSecondsFromMicroseconds * 1e6;
if (totalSecondsSharp > 0 && totalMicroseconds < 0) {
totalSecondsSharp -= 1;
totalMicroseconds += 1e6;
}
_days = (int)(totalSecondsSharp / SECONDSPERDAY);
_seconds = (int)(totalSecondsSharp - _days * SECONDSPERDAY);
if (_seconds < 0) {
_days--;
_seconds += (int)SECONDSPERDAY;
}
_microseconds = (int)(totalMicroseconds);
if (Math.Abs(_days) > MAXDAYS) {
throw PythonOps.OverflowError("days={0}; must have magnitude <= 999999999", _days);
}
}
public static timedelta __new__(CodeContext context, PythonType cls,
[DefaultParameterValue(0D)] double days,
[DefaultParameterValue(0D)] double seconds,
[DefaultParameterValue(0D)] double microseconds,
[DefaultParameterValue(0D)] double milliseconds,
[DefaultParameterValue(0D)] double minutes,
[DefaultParameterValue(0D)] double hours,
[DefaultParameterValue(0D)] double weeks) {
if (cls == DynamicHelpers.GetPythonTypeFromType(typeof(timedelta))) {
return new timedelta(days, seconds, microseconds, milliseconds, minutes, hours, weeks);
} else {
timedelta delta = cls.CreateInstance(context, days, seconds, microseconds, milliseconds, minutes, hours, weeks) as timedelta;
if (delta == null) throw PythonOps.TypeError("{0} is not a subclass of datetime.timedelta", cls);
return delta;
}
}
// instance attributes:
public int days {
get { return _days; }
}
public int seconds {
get { return _seconds; }
}
public int microseconds {
get { return _microseconds; }
}
internal TimeSpan TimeSpanWithDaysAndSeconds {
get {
if (!_fWithDaysAndSeconds) {
_tsWithDaysAndSeconds = new TimeSpan(_days, 0, 0, _seconds);
_fWithDaysAndSeconds = true;
}
return _tsWithDaysAndSeconds;
}
}
internal TimeSpan TimeSpanWithSeconds {
get {
if (!_fWithSeconds) {
_tsWithSeconds = TimeSpan.FromSeconds(_seconds);
_fWithSeconds = true;
}
return _tsWithSeconds;
}
}
// supported operations:
public static timedelta operator +(timedelta self, timedelta other) {
return new timedelta(self._days + other._days, self._seconds + other._seconds, self._microseconds + other._microseconds);
}
public static timedelta operator -(timedelta self, timedelta other) {
return new timedelta(self._days - other._days, self._seconds - other._seconds, self._microseconds - other._microseconds);
}
public static timedelta operator -(timedelta self) {
return new timedelta(-self._days, -self._seconds, -self._microseconds);
}
public static timedelta operator +(timedelta self) {
return new timedelta(self._days, self._seconds, self._microseconds);
}
public static timedelta operator *(timedelta self, int other) {
return new timedelta(self._days * other, self._seconds * other, self._microseconds * other);
}
public static timedelta operator *(int other, timedelta self) {
return new timedelta(self._days * other, self._seconds * other, self._microseconds * other);
}
public static timedelta operator /(timedelta self, int other) {
return new timedelta((double)self._days / other, (double)self._seconds / other, (double)self._microseconds / other);
}
public static timedelta operator *(timedelta self, BigInteger other) {
return self * (int)other;
}
public static timedelta operator *(BigInteger other, timedelta self) {
return (int)other * self;
}
public static timedelta operator /(timedelta self, BigInteger other) {
return self / (int)other;
}
public timedelta __pos__() { return +this; }
public timedelta __neg__() { return -this; }
public timedelta __abs__() { return (_days > 0) ? this : -this; }
[SpecialName]
public timedelta FloorDivide(int y) {
return this / y;
}
[SpecialName]
public timedelta ReverseFloorDivide(int y) {
return this / y;
}
public double total_seconds() {
var total_microseconds = (double) this.microseconds + (this.seconds + this.days * 24.0 * 3600.0) * 1000000.0;
return total_microseconds / 1000000.0;
}
public bool __nonzero__() {
return this._days != 0 || this._seconds != 0 || this._microseconds != 0;
}
public PythonTuple __reduce__() {
return PythonTuple.MakeTuple(
DynamicHelpers.GetPythonType(this),
PythonTuple.MakeTuple(_days, _seconds, _microseconds)
);
}
public static object __getnewargs__(int days, int seconds, int microseconds) {
return PythonTuple.MakeTuple(new timedelta(days, seconds, microseconds, 0, 0, 0, 0));
}
public override bool Equals(object obj) {
timedelta delta = obj as timedelta;
if (delta == null) return false;
return this._days == delta._days && this._seconds == delta._seconds && this._microseconds == delta._microseconds;
}
public override int GetHashCode() {
return this._days ^ this._seconds ^ this._microseconds;
}
public override string ToString() {
StringBuilder sb = new StringBuilder();
if (_days != 0) {
sb.Append(_days);
if (Math.Abs(_days) == 1)
sb.Append(" day, ");
else
sb.Append(" days, ");
}
sb.AppendFormat("{0}:{1:d2}:{2:d2}", TimeSpanWithSeconds.Hours, TimeSpanWithSeconds.Minutes, TimeSpanWithSeconds.Seconds);
if (_microseconds != 0)
sb.AppendFormat(".{0:d6}", _microseconds);
return sb.ToString();
}
#region Rich Comparison Members
private int CompareTo(object other) {
timedelta delta = other as timedelta;
if (delta == null)
throw PythonOps.TypeError("can't compare datetime.timedelta to {0}", PythonTypeOps.GetName(other));
int res = this._days - delta._days;
if (res != 0) return res;
res = this._seconds - delta._seconds;
if (res != 0) return res;
return this._microseconds - delta._microseconds;
}
public static bool operator >(timedelta self, object other) {
return self.CompareTo(other) > 0;
}
public static bool operator <(timedelta self, object other) {
return self.CompareTo(other) < 0;
}
public static bool operator >=(timedelta self, object other) {
return self.CompareTo(other) >= 0;
}
public static bool operator <=(timedelta self, object other) {
return self.CompareTo(other) <= 0;
}
#endregion
#region ICodeFormattable Members
public virtual string/*!*/ __repr__(CodeContext/*!*/ context) {
if (_seconds == 0 && _microseconds == 0) {
return String.Format("datetime.timedelta({0})", _days);
} else if (_microseconds == 0) {
return String.Format("datetime.timedelta({0}, {1})", _days, _seconds);
} else {
return String.Format("datetime.timedelta({0}, {1}, {2})", _days, _seconds, _microseconds);
}
}
#endregion
}
internal static void ThrowIfInvalid(timedelta delta, string funcname) {
if (delta != null) {
if (delta._microseconds != 0 || delta._seconds % 60 != 0) {
throw PythonOps.ValueError("tzinfo.{0}() must return a whole number of minutes", funcname);
}
int minutes = (int)(delta.TimeSpanWithDaysAndSeconds.TotalSeconds / 60);
if (Math.Abs(minutes) >= 1440) {
throw PythonOps.ValueError("tzinfo.{0}() returned {1}; must be in -1439 .. 1439", funcname, minutes);
}
}
}
internal enum InputKind { Year, Month, Day, Hour, Minute, Second, Microsecond }
internal static void ValidateInput(InputKind kind, int value) {
switch (kind) {
case InputKind.Year:
if (value > DateTime.MaxValue.Year || value < DateTime.MinValue.Year) {
throw PythonOps.ValueError("year is out of range");
}
break;
case InputKind.Month:
if (value > 12 || value < 1) {
throw PythonOps.ValueError("month must be in 1..12");
}
break;
case InputKind.Day:
// TODO: changing upper bound
if (value > 31 || value < 1) {
throw PythonOps.ValueError("day is out of range for month");
}
break;
case InputKind.Hour:
if (value > 23 || value < 0) {
throw PythonOps.ValueError("hour must be in 0..23");
}
break;
case InputKind.Minute:
if (value > 59 || value < 0) {
throw PythonOps.ValueError("minute must be in 0..59");
}
break;
case InputKind.Second:
if (value > 59 || value < 0) {
throw PythonOps.ValueError("second must be in 0..59");
}
break;
case InputKind.Microsecond:
if (value > 999999 || value < 0) {
throw PythonOps.ValueError("microsecond must be in 0..999999");
}
break;
}
}
internal static bool IsNaiveTimeZone(tzinfo tz) {
if (tz == null) return true;
if (tz.utcoffset(null) == null) return true;
return false;
}
internal static int CastToInt(object o) {
return o is BigInteger ? (int)(BigInteger)o : (int)o;
}
[PythonType]
public class date : ICodeFormattable {
internal DateTime _dateTime;
// class attributes
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")]
public static readonly date min = new date(new DateTime(1, 1, 1));
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")]
public static readonly date max = new date(new DateTime(9999, 12, 31));
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")]
public static readonly timedelta resolution = timedelta._DayResolution;
// Make this parameterless constructor internal
// so that the datetime module subclasses can use it,
// if this was protected instead, then you couldn't
// successfully call the public date constructor.
// Due to overload resolution failing.
// The protected version of this constructor matches
// the public constructor due to KeywordArgReturnBuilder
// related parameter processing,
internal date() { }
public date(int year, int month, int day) {
PythonDateTime.ValidateInput(InputKind.Year, year);
PythonDateTime.ValidateInput(InputKind.Month, month);
PythonDateTime.ValidateInput(InputKind.Day, day);
_dateTime = new DateTime(year, month, day);
}
internal date(DateTime value) {
_dateTime = value.Date; // no hour, minute, second
}
// other constructors, all class methods
public static object today() {
return new date(DateTime.Today);
}
public static date fromordinal(int d) {
if (d < 1) {
throw PythonOps.ValueError("ordinal must be >= 1");
}
return new date(min._dateTime.AddDays(d - 1));
}
public static date fromtimestamp(double timestamp) {
DateTime dt = PythonTime.TimestampToDateTime(timestamp);
dt = dt.AddSeconds(-PythonTime.timezone);
return new date(dt.Year, dt.Month, dt.Day);
}
// instance attributes
public int year {
get { return _dateTime.Year; }
}
public int month {
get { return _dateTime.Month; }
}
public int day {
get { return _dateTime.Day; }
}
internal DateTime InternalDateTime {
get { return _dateTime; }
set { _dateTime = value; }
}
public static implicit operator DateTime(date self) {
return self._dateTime;
}
// supported operations
public static date operator +([NotNull]date self, [NotNull]timedelta other) {
try {
return new date(self._dateTime.AddDays(other.days));
} catch {
throw PythonOps.OverflowError("date value out of range");
}
}
public static date operator +([NotNull]timedelta other, [NotNull]date self) {
try {
return new date(self._dateTime.AddDays(other.days));
} catch {
throw PythonOps.OverflowError("date value out of range");
}
}
public static date operator -(date self, timedelta delta) {
try {
return new date(self._dateTime.AddDays(-1 * delta.days));
} catch {
throw PythonOps.OverflowError("date value out of range");
}
}
public static timedelta operator -(date self, date other) {
TimeSpan ts = self._dateTime - other._dateTime;
return new timedelta(0, ts.TotalSeconds, ts.Milliseconds * 1000);
}
public virtual PythonTuple __reduce__() {
return PythonTuple.MakeTuple(DynamicHelpers.GetPythonType(this), PythonTuple.MakeTuple(_dateTime.Year, _dateTime.Month, _dateTime.Day));
}
public static object __getnewargs__(CodeContext context, int year, int month, int day) {
return PythonTuple.MakeTuple(new date(year, month, day));
}
public object replace() {
return this;
}
// instance methods
public virtual date replace(CodeContext/*!*/ context, [ParamDictionary]IDictionary<object, object> dict) {
int year2 = _dateTime.Year;
int month2 = _dateTime.Month;
int day2 = _dateTime.Day;
foreach (KeyValuePair<object, object> kvp in (IDictionary<object, object>)dict) {
string strVal = kvp.Key as string;
if (strVal == null) continue;
switch (strVal) {
case "year": year2 = CastToInt(kvp.Value); break;
case "month": month2 = CastToInt(kvp.Value); break;
case "day": day2 = CastToInt(kvp.Value); break;
default: throw PythonOps.TypeError("{0} is an invalid keyword argument for this function", kvp.Key);
}
}
return new date(year2, month2, day2);
}
public virtual object timetuple() {
return PythonTime.GetDateTimeTuple(_dateTime);
}
public int toordinal() {
return (_dateTime - min._dateTime).Days + 1;
}
public int weekday() { return PythonTime.Weekday(_dateTime); }
public int isoweekday() { return PythonTime.IsoWeekday(_dateTime); }
private DateTime FirstDayOfIsoYear(int year) {
DateTime firstDay = new DateTime(year, 1, 1);
DateTime firstIsoDay = firstDay;
switch (firstDay.DayOfWeek) {
case DayOfWeek.Sunday:
firstIsoDay = firstDay.AddDays(1);
break;
case DayOfWeek.Monday:
case DayOfWeek.Tuesday:
case DayOfWeek.Wednesday:
case DayOfWeek.Thursday:
firstIsoDay = firstDay.AddDays(-1 * ((int)firstDay.DayOfWeek - 1));
break;
case DayOfWeek.Friday:
firstIsoDay = firstDay.AddDays(3);
break;
case DayOfWeek.Saturday:
firstIsoDay = firstDay.AddDays(2);
break;
}
return firstIsoDay;
}
public PythonTuple isocalendar() {
DateTime firstDayOfLastIsoYear = FirstDayOfIsoYear(_dateTime.Year - 1);
DateTime firstDayOfThisIsoYear = FirstDayOfIsoYear(_dateTime.Year);
DateTime firstDayOfNextIsoYear = FirstDayOfIsoYear(_dateTime.Year + 1);
int year, days;
if (firstDayOfThisIsoYear <= _dateTime && _dateTime < firstDayOfNextIsoYear) {
year = _dateTime.Year;
days = (_dateTime - firstDayOfThisIsoYear).Days;
} else if (_dateTime < firstDayOfThisIsoYear) {
year = _dateTime.Year - 1;
days = (_dateTime - firstDayOfLastIsoYear).Days;
} else {
year = _dateTime.Year + 1;
days = (_dateTime - firstDayOfNextIsoYear).Days;
}
return PythonTuple.MakeTuple(year, days / 7 + 1, days % 7 + 1);
}
public string isoformat() {
return _dateTime.ToString("yyyy-MM-dd");
}
public override string ToString() {
return isoformat();
}
public string ctime() {
return _dateTime.ToString("ddd MMM ", CultureInfo.InvariantCulture) +
string.Format(CultureInfo.InvariantCulture, "{0,2}", _dateTime.Day) +
_dateTime.ToString(" HH:mm:ss yyyy", CultureInfo.InvariantCulture);
}
public virtual string strftime(CodeContext/*!*/ context, string dateFormat) {
return PythonTime.strftime(context, dateFormat, _dateTime, null);
}
public override bool Equals(object obj) {
if (obj == null) return false;
date other = obj as date;
if (other != null && !(obj is datetime)) {
return this._dateTime == other._dateTime;
} else {
return false;
}
}
public override int GetHashCode() {
return _dateTime.GetHashCode();
}
#region Rich Comparison Members
internal virtual int CompareTo(object other) {
date date = other as date;
return this._dateTime.CompareTo(date._dateTime);
}
internal bool CheckType(object other) {
return CheckType(other, true);
}
/// <summary>
/// Used to check the type to see if we can do a comparison. Returns true if we can
/// or false if we should return NotImplemented. May throw if the type's really wrong.
/// </summary>
internal bool CheckType(object other, bool shouldThrow) {
if (other == null) {
return CheckTypeError(other, shouldThrow);
}
if (other.GetType() != GetType()) {
// if timetuple is defined on the other object go ahead and let it try the compare,
// but only if it's a user-defined object
if (!(GetType() == typeof(date) && other.GetType() == typeof(datetime) ||
GetType() == typeof(datetime) & other.GetType() == typeof(date))) {
if (PythonOps.HasAttr(DefaultContext.Default, other, "timetuple")) {
return false;
}
}
return CheckTypeError(other, shouldThrow);
}
return true;
}
private static bool CheckTypeError(object other, bool shouldThrow) {
if (shouldThrow) {
throw PythonOps.TypeError("can't compare datetime.date to {0}", PythonTypeOps.GetName(other));
} else {
return true;
}
}
[return: MaybeNotImplemented]
public static object operator >(date self, object other) {
if (!self.CheckType(other)) return NotImplementedType.Value;
return Microsoft.Scripting.Runtime.ScriptingRuntimeHelpers.BooleanToObject(self.CompareTo(other) > 0);
}
[return: MaybeNotImplemented]
public static object operator <(date self, object other) {
if (!self.CheckType(other)) return NotImplementedType.Value;
return Microsoft.Scripting.Runtime.ScriptingRuntimeHelpers.BooleanToObject(self.CompareTo(other) < 0);
}
[return: MaybeNotImplemented]
public static object operator >=(date self, object other) {
if (!self.CheckType(other)) return NotImplementedType.Value;
return Microsoft.Scripting.Runtime.ScriptingRuntimeHelpers.BooleanToObject(self.CompareTo(other) >= 0);
}
[return: MaybeNotImplemented]
public static object operator <=(date self, object other) {
if (!self.CheckType(other)) return NotImplementedType.Value;
return Microsoft.Scripting.Runtime.ScriptingRuntimeHelpers.BooleanToObject(self.CompareTo(other) <= 0);
}
public object __eq__(object other) {
if (!CheckType(other, false)) return NotImplementedType.Value;
return Equals(other);
}
public object __ne__(object other) {
if (!CheckType(other, false)) return NotImplementedType.Value;
return !Equals(other);
}
#endregion
#region ICodeFormattable Members
public virtual string/*!*/ __repr__(CodeContext/*!*/ context) {
return string.Format("datetime.date({0}, {1}, {2})", _dateTime.Year, _dateTime.Month, _dateTime.Day);
}
public virtual string __format__(CodeContext/*!*/ context, string dateFormat){
if (string.IsNullOrEmpty(dateFormat)) {
return PythonOps.ToString(context, this);
} else {
return strftime(context, dateFormat);
}
}
#endregion
}
[PythonType]
public class datetime : date, ICodeFormattable {
internal int _lostMicroseconds;
internal tzinfo _tz;
// class attributes
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")]
public new static readonly datetime max = new datetime(DateTime.MaxValue, 999, null);
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")]
public new static readonly datetime min = new datetime(DateTime.MinValue, 0, null);
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")]
public new static readonly timedelta resolution = timedelta.resolution;
private UnifiedDateTime _utcDateTime;
private const long TicksPerMicrosecond = TimeSpan.TicksPerMillisecond/1000;
public datetime(int year,
int month,
int day,
[DefaultParameterValue(0)]int hour,
[DefaultParameterValue(0)]int minute,
[DefaultParameterValue(0)]int second,
[DefaultParameterValue(0)]int microsecond,
[DefaultParameterValue(null)]tzinfo tzinfo) {
PythonDateTime.ValidateInput(InputKind.Year, year);
PythonDateTime.ValidateInput(InputKind.Month, month);
PythonDateTime.ValidateInput(InputKind.Day, day);
PythonDateTime.ValidateInput(InputKind.Hour, hour);
PythonDateTime.ValidateInput(InputKind.Minute, minute);
PythonDateTime.ValidateInput(InputKind.Second, second);
PythonDateTime.ValidateInput(InputKind.Microsecond, microsecond);
InternalDateTime = new DateTime(year, month, day, hour, minute, second, microsecond / 1000);
_lostMicroseconds = microsecond % 1000;
_tz = tzinfo;
}
public datetime([NotNull]string str) {
if (str.Length != 10) {
throw PythonOps.TypeError("an integer is required");
}
int microSeconds = (((int)str[7]) << 16) | ((int)str[8] << 8) | (int)str[9];
int month = (int)str[2];
if (month == 0 || month > 12) {
throw PythonOps.TypeError("invalid month");
}
InternalDateTime = new DateTime(
(((int)str[0]) << 8) | (int)str[1],
month,
(int)str[3],
(int)str[4],
(int)str[5],
(int)str[6],
microSeconds / 1000
);
_lostMicroseconds = microsecond % 1000;
}
public datetime([NotNull]string str, [NotNull]tzinfo tzinfo)
: this(str) {
_tz = tzinfo;
}
private void Initialize(int year, int month, int day, int hour, int minute, int second, int microsecond, tzinfo tzinfo) {
}
public datetime(DateTime dt)
: this(dt, null) {
}
public datetime(DateTime dt, tzinfo tzinfo)
: this(dt, (int)((dt.Ticks / TicksPerMicrosecond) % 1000), tzinfo) {
}
// just present to match CPython's error messages...
public datetime(params object[] args) {
if (args.Length < 3) {
throw PythonOps.TypeError("function takes at least 3 arguments ({0} given)", args.Length);
} else if (args.Length > 8) {
throw PythonOps.TypeError("function takes at most 8 arguments ({0} given)", args.Length);
}
for (int i = 0; i < args.Length && i < 7; i++) { // 8 is offsetof tzinfo
if (!(args[i] is int)) {
throw PythonOps.TypeError("an integer is required");
}
}
if (args.Length > 7 && !(args[7] is tzinfo || args[7] == null)) {
throw PythonOps.TypeError("tzinfo argument must be None or of a tzinfo subclass, not type '{0}'", PythonTypeOps.GetName(args[7]));
}
// the above cases should cover all binding failures...
throw new InvalidOperationException();
}
internal datetime(DateTime dt, int lostMicroseconds, tzinfo tzinfo) {
this.InternalDateTime = new DateTime(dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, dt.Second);
this._lostMicroseconds = dt.Millisecond * 1000 + lostMicroseconds;
this._tz = tzinfo;
// make sure both are positive, and lostMicroseconds < 1000
if (_lostMicroseconds < 0) {
try {
InternalDateTime = InternalDateTime.AddMilliseconds(_lostMicroseconds / 1000 - 1);
} catch {
throw PythonOps.OverflowError("date value out of range");
}
_lostMicroseconds = _lostMicroseconds % 1000 + 1000;
}
if (_lostMicroseconds > 999) {
try {
InternalDateTime = InternalDateTime.AddMilliseconds(_lostMicroseconds / 1000);
} catch {
throw PythonOps.OverflowError("date value out of range");
}
_lostMicroseconds = _lostMicroseconds % 1000;
}
}
// other constructors, all class methods:
public static object now([DefaultParameterValue(null)]tzinfo tz) {
if (tz != null) {
return tz.fromutc(new datetime(DateTime.UtcNow, 0, tz));
} else {
return new datetime(DateTime.Now, 0, null);
}
}
public static object utcnow() {
return new datetime(DateTime.UtcNow, 0, null);
}
public new static object today() {
return new datetime(DateTime.Now, 0, null);
}
public static object fromtimestamp(double timestamp, [DefaultParameterValue(null)] tzinfo tz) {
DateTime dt = PythonTime.TimestampToDateTime(timestamp);
dt = dt.AddSeconds(-PythonTime.timezone);
if (tz != null) {
dt = dt.ToUniversalTime();
datetime pdtc = new datetime(dt, tz);
return tz.fromutc(pdtc);
} else {
return new datetime(dt);
}
}
public static datetime utcfromtimestamp(double timestamp) {
DateTime dt = new DateTime(PythonTime.TimestampToTicks(timestamp), DateTimeKind.Utc);
return new datetime(dt, 0, null);
}
public new static datetime fromordinal(int d) {
if (d < 1) {
throw PythonOps.ValueError("ordinal must be >= 1");
}
return new datetime(DateTime.MinValue + new TimeSpan(d - 1, 0, 0, 0), 0, null);
}
public static object combine(date date, time time) {
return new datetime(date.year, date.month, date.day, time.hour, time.minute, time.second, time.microsecond, time.tzinfo);
}
// instance attributes
public int hour {
get { return InternalDateTime.Hour; }
}
public int minute {
get { return InternalDateTime.Minute; }
}
public int second {
get { return InternalDateTime.Second; }
}
public int microsecond {
get { return InternalDateTime.Millisecond * 1000 + _lostMicroseconds; }
}
public object tzinfo {
get { return _tz; }
}
private UnifiedDateTime UtcDateTime {
get {
if (_utcDateTime == null) {
_utcDateTime = new UnifiedDateTime();
_utcDateTime.DateTime = InternalDateTime;
_utcDateTime.LostMicroseconds = _lostMicroseconds;
timedelta delta = this.utcoffset();
if (delta != null) {
datetime utced = this - delta;
_utcDateTime.DateTime = utced.InternalDateTime;
_utcDateTime.LostMicroseconds = utced._lostMicroseconds;
}
}
return _utcDateTime;
}
}
// supported operations
public static datetime operator +([NotNull]datetime date, [NotNull]timedelta delta) {
try {
return new datetime(date.InternalDateTime.Add(delta.TimeSpanWithDaysAndSeconds), delta._microseconds + date._lostMicroseconds, date._tz);
} catch (ArgumentException) {
throw new OverflowException("date value out of range");
}
}
public static datetime operator +([NotNull]timedelta delta, [NotNull]datetime date) {
try {
return new datetime(date.InternalDateTime.Add(delta.TimeSpanWithDaysAndSeconds), delta._microseconds + date._lostMicroseconds, date._tz);
} catch (ArgumentException) {
throw new OverflowException("date value out of range");
}
}
public static datetime operator -(datetime date, timedelta delta) {
return new datetime(date.InternalDateTime.Subtract(delta.TimeSpanWithDaysAndSeconds), date._lostMicroseconds - delta._microseconds, date._tz);
}
public static timedelta operator -(datetime date, datetime other) {
if (CheckTzInfoBeforeCompare(date, other)) {
return new timedelta(date.InternalDateTime - other.InternalDateTime, date._lostMicroseconds - other._lostMicroseconds);
} else {
return new timedelta(date.UtcDateTime.DateTime - other.UtcDateTime.DateTime, date.UtcDateTime.LostMicroseconds - other.UtcDateTime.LostMicroseconds);
}
}
// instance methods
public date date() {
return new date(year, month, day);
}
[Documentation("gets the datetime w/o the time zone component")]
public time time() {
return new time(hour, minute, second, microsecond, null);
}
public object timetz() {
return new time(hour, minute, second, microsecond, _tz);
}
[Documentation("gets a new datetime object with the fields provided as keyword arguments replaced.")]
public override date replace(CodeContext/*!*/ context, [ParamDictionary]IDictionary<object, object> dict) {
int lyear = year;
int lmonth = month;
int lday = day;
int lhour = hour;
int lminute = minute;
int lsecond = second;
int lmicrosecond = microsecond;
tzinfo tz = _tz;
foreach (KeyValuePair<object, object> kvp in (IDictionary<object, object>)dict) {
string key = kvp.Key as string;
if (key == null) continue;
switch (key) {
case "year":
lyear = CastToInt(kvp.Value);
break;
case "month":
lmonth = CastToInt(kvp.Value);
break;
case "day":
lday = CastToInt(kvp.Value);
break;
case "hour":
lhour = CastToInt(kvp.Value);
break;
case "minute":
lminute = CastToInt(kvp.Value);
break;
case "second":
lsecond = CastToInt(kvp.Value);
break;
case "microsecond":
lmicrosecond = CastToInt(kvp.Value);
break;
case "tzinfo":
tz = kvp.Value as tzinfo;
break;
default:
throw PythonOps.TypeError("{0} is an invalid keyword argument for this function", kvp.Key);
}
}
return new datetime(lyear, lmonth, lday, lhour, lminute, lsecond, lmicrosecond, tz);
}
public object astimezone(tzinfo tz) {
if (tz == null)
throw PythonOps.TypeError("astimezone() argument 1 must be datetime.tzinfo, not None");
if (_tz == null)
throw PythonOps.ValueError("astimezone() cannot be applied to a naive datetime");
if (tz == _tz)
return this;