|
32 | 32 |
|
33 | 33 | import sys
|
34 | 34 | import decimal
|
35 |
| -import time |
36 |
| - |
37 | 35 | from datetime import datetime as Timestamp, date as Date, time as Time
|
38 | 36 | from datetime import timedelta as TimeDelta
|
| 37 | +from datetime import tzinfo # pylint: disable=unused-import |
39 | 38 |
|
40 | 39 | try:
|
41 | 40 | from typing import Tuple, Union # pylint: disable=unused-import
|
42 | 41 | except ImportError:
|
43 | 42 | pass
|
44 | 43 |
|
| 44 | +import tzlocal |
45 | 45 | from .exception import DataError
|
| 46 | +from .calendar import ymd2day, day2ymd |
| 47 | + |
| 48 | +# zoneinfo.ZoneInfo is preferred but not introduced until python3.9 |
| 49 | +if sys.version_info >= (3, 9): |
| 50 | + # used for python>=3.9 with support for zoneinfo.ZoneInfo |
| 51 | + from zoneinfo import ZoneInfo # pylint: disable=unused-import |
| 52 | + from datetime import timezone |
| 53 | + UTC = timezone.utc |
| 54 | + |
| 55 | + def utc_TimeStamp(year, month, day, hour=0, minute=0, second=0, microsecond=0): |
| 56 | + # type: (int, int, int, int, int, int, int) -> Timestamp |
| 57 | + """ |
| 58 | + timezone aware datetime with UTC timezone. |
| 59 | + """ |
| 60 | + return Timestamp(year=year, month=month, day=day, |
| 61 | + hour=hour, minute=minute, second=second, |
| 62 | + microsecond=microsecond, tzinfo=UTC) |
| 63 | + |
| 64 | + def timezone_aware(tstamp, tz_info): |
| 65 | + # type: (Timestamp, tzinfo) -> Timestamp |
| 66 | + return tstamp.replace(tzinfo=tz_info) |
| 67 | + |
| 68 | +else: |
| 69 | + # used for python<3.9 without support for zoneinfo.ZoneInfo |
| 70 | + from pytz import utc as UTC |
| 71 | + |
| 72 | + def utc_TimeStamp(year, month, day, hour=0, minute=0, second=0, microsecond=0): |
| 73 | + # type: (int, int, int, int, int, int, int) -> Timestamp |
| 74 | + """ |
| 75 | + timezone aware datetime with UTC timezone. |
| 76 | + """ |
| 77 | + dt = Timestamp(year=year, month=month, day=day, |
| 78 | + hour=hour, minute=minute, second=second, microsecond=microsecond) |
| 79 | + return UTC.localize(dt, is_dst=None) |
| 80 | + |
| 81 | + def timezone_aware(tstamp, tz_info): |
| 82 | + # type: (Timestamp, tzinfo) -> Timestamp |
| 83 | + return tz_info.localize(tstamp, is_dst=None) # type: ignore[attr-defined] |
46 | 84 |
|
47 | 85 | isP2 = sys.version[0] == '2'
|
| 86 | +TICKSDAY = 86400 |
| 87 | +LOCALZONE = tzlocal.get_localzone() |
| 88 | + |
| 89 | +if hasattr(tzlocal, 'get_localzone_name'): |
| 90 | + # tzlocal >= 3.0 |
| 91 | + LOCALZONE_NAME = tzlocal.get_localzone_name() |
| 92 | +else: |
| 93 | + # tzlocal < 3.0 |
| 94 | + # local_tz is a pytz.tzinfo object. should have zone attribute |
| 95 | + LOCALZONE_NAME = getattr(LOCALZONE, 'zone') |
48 | 96 |
|
49 | 97 |
|
50 | 98 | class Binary(bytes):
|
@@ -83,56 +131,138 @@ def string(self):
|
83 | 131 | def DateFromTicks(ticks):
|
84 | 132 | # type: (int) -> Date
|
85 | 133 | """Convert ticks to a Date object."""
|
86 |
| - return Date(*time.localtime(ticks)[:3]) |
| 134 | + y, m, d = day2ymd(ticks // TICKSDAY) |
| 135 | + return Date(year=y, month=m, day=d) |
87 | 136 |
|
88 | 137 |
|
89 |
| -def TimeFromTicks(ticks, micro=0): |
90 |
| - # type: (int, int) -> Time |
| 138 | +def TimeFromTicks(ticks, micro=0, zoneinfo=LOCALZONE): |
| 139 | + # type: (int, int, tzinfo) -> Time |
91 | 140 | """Convert ticks to a Time object."""
|
92 |
| - return Time(*time.localtime(ticks)[3:6] + (micro,)) |
93 | 141 |
|
94 |
| - |
95 |
| -def TimestampFromTicks(ticks, micro=0): |
96 |
| - # type: (int, int) -> Timestamp |
| 142 | + # NuoDB release <= 7.0, it's possible that ticks is |
| 143 | + # expressed as a Timestamp and not just a Time. |
| 144 | + # NuoDB release > 7.0, ticks will be between (-TICKSDAY,2*TICKSDAY) |
| 145 | + |
| 146 | + if ticks < -TICKSDAY or ticks > 2 * TICKSDAY: |
| 147 | + dt = TimestampFromTicks(ticks, micro, zoneinfo) |
| 148 | + return dt.time() |
| 149 | + |
| 150 | + seconds = ticks % TICKSDAY |
| 151 | + hours = (seconds // 3600) % 24 |
| 152 | + minutes = (seconds // 60) % 60 |
| 153 | + seconds = seconds % 60 |
| 154 | + tstamp = Timestamp.combine(Date(1970, 1, 1), |
| 155 | + Time(hour=hours, |
| 156 | + minute=minutes, |
| 157 | + second=seconds, |
| 158 | + microsecond=micro) |
| 159 | + ) |
| 160 | + # remove offset that the engine added |
| 161 | + utcoffset = zoneinfo.utcoffset(tstamp) |
| 162 | + if utcoffset: |
| 163 | + tstamp += utcoffset |
| 164 | + # returns naive time , should a timezone-aware time be returned instead |
| 165 | + return tstamp.time() |
| 166 | + |
| 167 | + |
| 168 | +def TimestampFromTicks(ticks, micro=0, zoneinfo=LOCALZONE): |
| 169 | + # type: (int, int, tzinfo) -> Timestamp |
97 | 170 | """Convert ticks to a Timestamp object."""
|
98 |
| - return Timestamp(*time.localtime(ticks)[:6] + (micro,)) |
| 171 | + day = ticks // TICKSDAY |
| 172 | + y, m, d = day2ymd(day) |
| 173 | + timeticks = ticks % TICKSDAY |
| 174 | + hour = timeticks // 3600 |
| 175 | + sec = timeticks % 3600 |
| 176 | + min = sec // 60 |
| 177 | + sec %= 60 |
| 178 | + |
| 179 | + # this requires both utc and current session to be between year 1 and year 9999 inclusive. |
| 180 | + # nuodb could store a timestamp that is east of utc where utc would be year 10000. |
| 181 | + if y < 10000: |
| 182 | + dt = utc_TimeStamp(year=y, month=m, day=d, hour=hour, |
| 183 | + minute=min, second=sec, microsecond=micro) |
| 184 | + dt = dt.astimezone(zoneinfo) |
| 185 | + else: |
| 186 | + # shift one day. |
| 187 | + dt = utc_TimeStamp(year=9999, month=12, day=31, hour=hour, |
| 188 | + minute=min, second=sec, microsecond=micro) |
| 189 | + dt = dt.astimezone(zoneinfo) |
| 190 | + # add day back. |
| 191 | + dt += TimeDelta(days=1) |
| 192 | + # returns timezone-aware datetime |
| 193 | + return dt |
99 | 194 |
|
100 | 195 |
|
101 | 196 | def DateToTicks(value):
|
102 | 197 | # type: (Date) -> int
|
103 | 198 | """Convert a Date object to ticks."""
|
104 |
| - timeStruct = Date(value.year, value.month, value.day).timetuple() |
105 |
| - try: |
106 |
| - return int(time.mktime(timeStruct)) |
107 |
| - except Exception: |
108 |
| - raise DataError("Year out of range") |
109 |
| - |
110 |
| - |
111 |
| -def TimeToTicks(value): |
112 |
| - # type: (Time) -> Tuple[int, int] |
| 199 | + day = ymd2day(value.year, value.month, value.day) |
| 200 | + return day * TICKSDAY |
| 201 | + |
| 202 | + |
| 203 | +def _packtime(seconds, microseconds): |
| 204 | + # type: (int, int) -> Tuple[int,int] |
| 205 | + if microseconds: |
| 206 | + ndiv = 0 |
| 207 | + shiftr = 1000000 |
| 208 | + shiftl = 1 |
| 209 | + while (microseconds % shiftr): |
| 210 | + shiftr //= 10 |
| 211 | + shiftl *= 10 |
| 212 | + ndiv += 1 |
| 213 | + return (seconds * shiftl + microseconds // shiftr, ndiv) |
| 214 | + else: |
| 215 | + return (seconds, 0) |
| 216 | + |
| 217 | + |
| 218 | +def TimeToTicks(value, zoneinfo=LOCALZONE): |
| 219 | + # type: (Time, tzinfo) -> Tuple[int, int] |
113 | 220 | """Convert a Time object to ticks."""
|
114 |
| - timeStruct = TimeDelta(hours=value.hour, minutes=value.minute, |
115 |
| - seconds=value.second, |
116 |
| - microseconds=value.microsecond) |
117 |
| - timeDec = decimal.Decimal(str(timeStruct.total_seconds())) |
118 |
| - return (int((timeDec + time.timezone) * 10**abs(timeDec.as_tuple()[2])), |
119 |
| - abs(timeDec.as_tuple()[2])) |
120 |
| - |
121 |
| - |
122 |
| -def TimestampToTicks(value): |
123 |
| - # type: (Timestamp) -> Tuple[int, int] |
| 221 | + epoch = Date(1970, 1, 1) |
| 222 | + tz_info = value.tzinfo |
| 223 | + if not tz_info: |
| 224 | + tz_info = zoneinfo |
| 225 | + |
| 226 | + my_time = Timestamp.combine(epoch, Time(hour=value.hour, |
| 227 | + minute=value.minute, |
| 228 | + second=value.second, |
| 229 | + microsecond=value.microsecond |
| 230 | + )) |
| 231 | + my_time = timezone_aware(my_time, tz_info) |
| 232 | + |
| 233 | + utc_time = Timestamp.combine(epoch, Time()) |
| 234 | + utc_time = timezone_aware(utc_time, UTC) |
| 235 | + |
| 236 | + td = my_time - utc_time |
| 237 | + |
| 238 | + # fence time within a day range |
| 239 | + if td < TimeDelta(0): |
| 240 | + td = td + TimeDelta(days=1) |
| 241 | + if td > TimeDelta(days=1): |
| 242 | + td = td - TimeDelta(days=1) |
| 243 | + |
| 244 | + time_dec = decimal.Decimal(str(td.total_seconds())) |
| 245 | + exponent = time_dec.as_tuple()[2] |
| 246 | + if not isinstance(exponent, int): |
| 247 | + # this should not occur |
| 248 | + raise ValueError("Invalid exponent in Decimal: %r" % exponent) |
| 249 | + return (int(time_dec * 10**abs(exponent)), abs(exponent)) |
| 250 | + |
| 251 | + |
| 252 | +def TimestampToTicks(value, zoneinfo=LOCALZONE): |
| 253 | + # type: (Timestamp, tzinfo) -> Tuple[int, int] |
124 | 254 | """Convert a Timestamp object to ticks."""
|
125 |
| - timeStruct = Timestamp(value.year, value.month, value.day, value.hour, |
126 |
| - value.minute, value.second).timetuple() |
127 |
| - try: |
128 |
| - if not value.microsecond: |
129 |
| - return (int(time.mktime(timeStruct)), 0) |
130 |
| - micro = decimal.Decimal(value.microsecond) / decimal.Decimal(1000000) |
131 |
| - t1 = decimal.Decimal(int(time.mktime(timeStruct))) + micro |
132 |
| - tlen = len(str(micro)) - 2 |
133 |
| - return (int(t1 * decimal.Decimal(int(10**tlen))), tlen) |
134 |
| - except Exception: |
135 |
| - raise DataError("Year out of range") |
| 255 | + # if naive timezone then leave date/time but change tzinfo to |
| 256 | + # be connection's timezone. |
| 257 | + if value.tzinfo is None: |
| 258 | + value = timezone_aware(value, zoneinfo) |
| 259 | + dt = value.astimezone(UTC) |
| 260 | + timesecs = ymd2day(dt.year, dt.month, dt.day) * TICKSDAY |
| 261 | + timesecs += dt.hour * 3600 |
| 262 | + timesecs += dt.minute * 60 |
| 263 | + timesecs += dt.second |
| 264 | + packedtime = _packtime(timesecs, dt.microsecond) |
| 265 | + return packedtime |
136 | 266 |
|
137 | 267 |
|
138 | 268 | class TypeObject(object):
|
|
0 commit comments