Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/pendulum/__init__.py: 59%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

161 statements  

1from __future__ import annotations 

2 

3import datetime as _datetime 

4 

5from functools import cache 

6from typing import TYPE_CHECKING 

7from typing import Any 

8from typing import Union 

9from typing import cast 

10from typing import overload 

11 

12from pendulum.constants import DAYS_PER_WEEK 

13from pendulum.constants import HOURS_PER_DAY 

14from pendulum.constants import MINUTES_PER_HOUR 

15from pendulum.constants import MONTHS_PER_YEAR 

16from pendulum.constants import SECONDS_PER_DAY 

17from pendulum.constants import SECONDS_PER_HOUR 

18from pendulum.constants import SECONDS_PER_MINUTE 

19from pendulum.constants import WEEKS_PER_YEAR 

20from pendulum.constants import YEARS_PER_CENTURY 

21from pendulum.constants import YEARS_PER_DECADE 

22from pendulum.date import Date 

23from pendulum.datetime import DateTime 

24from pendulum.day import WeekDay 

25from pendulum.duration import Duration 

26from pendulum.formatting import Formatter 

27from pendulum.helpers import format_diff 

28from pendulum.helpers import get_locale 

29from pendulum.helpers import locale 

30from pendulum.helpers import set_locale 

31from pendulum.helpers import week_ends_at 

32from pendulum.helpers import week_starts_at 

33from pendulum.interval import Interval 

34from pendulum.parser import parse as parse 

35from pendulum.time import Time 

36from pendulum.tz import UTC 

37from pendulum.tz import fixed_timezone 

38from pendulum.tz import local_timezone 

39from pendulum.tz import set_local_timezone 

40from pendulum.tz import test_local_timezone 

41from pendulum.tz import timezones 

42from pendulum.tz.timezone import FixedTimezone 

43from pendulum.tz.timezone import Timezone 

44 

45 

46MONDAY = WeekDay.MONDAY 

47TUESDAY = WeekDay.TUESDAY 

48WEDNESDAY = WeekDay.WEDNESDAY 

49THURSDAY = WeekDay.THURSDAY 

50FRIDAY = WeekDay.FRIDAY 

51SATURDAY = WeekDay.SATURDAY 

52SUNDAY = WeekDay.SUNDAY 

53 

54_TEST_NOW: DateTime | None = None 

55_LOCALE = "en" 

56_WEEK_STARTS_AT: WeekDay = WeekDay.MONDAY 

57_WEEK_ENDS_AT: WeekDay = WeekDay.SUNDAY 

58 

59_formatter = Formatter() 

60 

61 

62@overload 

63def timezone(name: int) -> FixedTimezone: ... 

64 

65 

66@overload 

67def timezone(name: str) -> Timezone: ... 

68 

69 

70@overload 

71def timezone(name: str | int) -> Timezone | FixedTimezone: ... 

72 

73 

74def timezone(name: str | int) -> Timezone | FixedTimezone: 

75 """ 

76 Return a Timezone instance given its name. 

77 """ 

78 if isinstance(name, int): 

79 return fixed_timezone(name) 

80 

81 if name.lower() == "utc": 

82 return UTC 

83 

84 return Timezone(name) 

85 

86 

87def _safe_timezone( 

88 obj: str | float | _datetime.tzinfo | Timezone | FixedTimezone | None, 

89 dt: _datetime.datetime | None = None, 

90) -> Timezone | FixedTimezone: 

91 """ 

92 Creates a timezone instance 

93 from a string, Timezone, TimezoneInfo or integer offset. 

94 """ 

95 if isinstance(obj, (Timezone, FixedTimezone)): 

96 return obj 

97 

98 if obj is None or obj == "local": 

99 return local_timezone() 

100 

101 if isinstance(obj, (int, float)): 

102 obj = int(obj * 60 * 60) 

103 elif isinstance(obj, _datetime.tzinfo): 

104 # zoneinfo 

105 if hasattr(obj, "key"): 

106 obj = obj.key 

107 # pytz 

108 elif hasattr(obj, "localize"): 

109 obj = obj.zone # type: ignore[attr-defined] 

110 elif obj.tzname(None) == "UTC": 

111 return UTC 

112 else: 

113 offset = obj.utcoffset(dt) 

114 

115 if offset is None: 

116 offset = _datetime.timedelta(0) 

117 

118 obj = int(offset.total_seconds()) 

119 

120 obj = cast("Union[str, int]", obj) 

121 

122 return timezone(obj) 

123 

124 

125# Public API 

126def datetime( 

127 year: int, 

128 month: int, 

129 day: int, 

130 hour: int = 0, 

131 minute: int = 0, 

132 second: int = 0, 

133 microsecond: int = 0, 

134 tz: str | float | Timezone | FixedTimezone | _datetime.tzinfo | None = UTC, 

135 fold: int = 1, 

136 raise_on_unknown_times: bool = False, 

137) -> DateTime: 

138 """ 

139 Creates a new DateTime instance from a specific date and time. 

140 """ 

141 return DateTime.create( 

142 year, 

143 month, 

144 day, 

145 hour=hour, 

146 minute=minute, 

147 second=second, 

148 microsecond=microsecond, 

149 tz=tz, 

150 fold=fold, 

151 raise_on_unknown_times=raise_on_unknown_times, 

152 ) 

153 

154 

155def local( 

156 year: int, 

157 month: int, 

158 day: int, 

159 hour: int = 0, 

160 minute: int = 0, 

161 second: int = 0, 

162 microsecond: int = 0, 

163) -> DateTime: 

164 """ 

165 Return a DateTime in the local timezone. 

166 """ 

167 return datetime( 

168 year, month, day, hour, minute, second, microsecond, tz=local_timezone() 

169 ) 

170 

171 

172def naive( 

173 year: int, 

174 month: int, 

175 day: int, 

176 hour: int = 0, 

177 minute: int = 0, 

178 second: int = 0, 

179 microsecond: int = 0, 

180 fold: int = 1, 

181) -> DateTime: 

182 """ 

183 Return a naive DateTime. 

184 """ 

185 return DateTime(year, month, day, hour, minute, second, microsecond, fold=fold) 

186 

187 

188def date(year: int, month: int, day: int) -> Date: 

189 """ 

190 Create a new Date instance. 

191 """ 

192 return Date(year, month, day) 

193 

194 

195def time(hour: int, minute: int = 0, second: int = 0, microsecond: int = 0) -> Time: 

196 """ 

197 Create a new Time instance. 

198 """ 

199 return Time(hour, minute, second, microsecond) 

200 

201 

202@overload 

203def instance( 

204 obj: _datetime.datetime, 

205 tz: str | Timezone | FixedTimezone | _datetime.tzinfo | None = UTC, 

206) -> DateTime: ... 

207 

208 

209@overload 

210def instance( 

211 obj: _datetime.date, 

212 tz: str | Timezone | FixedTimezone | _datetime.tzinfo | None = UTC, 

213) -> Date: ... 

214 

215 

216@overload 

217def instance( 

218 obj: _datetime.time, 

219 tz: str | Timezone | FixedTimezone | _datetime.tzinfo | None = UTC, 

220) -> Time: ... 

221 

222 

223def instance( 

224 obj: _datetime.datetime | _datetime.date | _datetime.time, 

225 tz: str | Timezone | FixedTimezone | _datetime.tzinfo | None = UTC, 

226) -> DateTime | Date | Time: 

227 """ 

228 Create a DateTime/Date/Time instance from a datetime/date/time native one. 

229 """ 

230 if isinstance(obj, (DateTime, Date, Time)): 

231 return obj 

232 

233 if isinstance(obj, _datetime.date) and not isinstance(obj, _datetime.datetime): 

234 return date(obj.year, obj.month, obj.day) 

235 

236 if isinstance(obj, _datetime.time): 

237 return Time.instance(obj, tz=tz) 

238 

239 return DateTime.instance(obj, tz=tz) 

240 

241 

242def now(tz: str | Timezone | None = None) -> DateTime: 

243 """ 

244 Get a DateTime instance for the current date and time. 

245 """ 

246 return DateTime.now(tz) 

247 

248 

249def today(tz: str | Timezone = "local") -> DateTime: 

250 """ 

251 Create a DateTime instance for today. 

252 """ 

253 return now(tz).start_of("day") 

254 

255 

256def tomorrow(tz: str | Timezone = "local") -> DateTime: 

257 """ 

258 Create a DateTime instance for tomorrow. 

259 """ 

260 return today(tz).add(days=1) 

261 

262 

263def yesterday(tz: str | Timezone = "local") -> DateTime: 

264 """ 

265 Create a DateTime instance for yesterday. 

266 """ 

267 return today(tz).subtract(days=1) 

268 

269 

270def from_format( 

271 string: str, 

272 fmt: str, 

273 tz: str | Timezone = UTC, 

274 locale: str | None = None, 

275) -> DateTime: 

276 """ 

277 Creates a DateTime instance from a specific format. 

278 """ 

279 parts = _formatter.parse(string, fmt, now(tz=tz), locale=locale) 

280 if parts["tz"] is None: 

281 parts["tz"] = tz 

282 

283 return datetime(**parts) 

284 

285 

286def from_timestamp(timestamp: int | float, tz: str | Timezone = UTC) -> DateTime: 

287 """ 

288 Create a DateTime instance from a timestamp. 

289 """ 

290 dt = _datetime.datetime.fromtimestamp(timestamp, tz=UTC) 

291 

292 dt = datetime( 

293 dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, dt.microsecond 

294 ) 

295 

296 if tz is not UTC or tz != "UTC": 

297 dt = dt.in_timezone(tz) 

298 

299 return dt 

300 

301 

302def duration( 

303 days: float = 0, 

304 seconds: float = 0, 

305 microseconds: float = 0, 

306 milliseconds: float = 0, 

307 minutes: float = 0, 

308 hours: float = 0, 

309 weeks: float = 0, 

310 years: float = 0, 

311 months: float = 0, 

312) -> Duration: 

313 """ 

314 Create a Duration instance. 

315 """ 

316 return Duration( 

317 days=days, 

318 seconds=seconds, 

319 microseconds=microseconds, 

320 milliseconds=milliseconds, 

321 minutes=minutes, 

322 hours=hours, 

323 weeks=weeks, 

324 years=years, 

325 months=months, 

326 ) 

327 

328 

329def interval( 

330 start: DateTime, end: DateTime, absolute: bool = False 

331) -> Interval[DateTime]: 

332 """ 

333 Create an Interval instance. 

334 """ 

335 return Interval(start, end, absolute=absolute) 

336 

337 

338if TYPE_CHECKING: 

339 from pendulum.testing.traveller import Traveller 

340 

341 _traveller = Traveller(DateTime) 

342 freeze = _traveller.freeze 

343 travel = _traveller.travel 

344 travel_to = _traveller.travel_to 

345 travel_back = _traveller.travel_back 

346else: 

347 # We do this in an if-not-typing block so we don't have to duplicate the function signatures. 

348 @cache 

349 def _traveller() -> Traveller: 

350 # Lazy load this, so we don't eagerly load Pytest if we don't need to 

351 from pendulum.testing.traveller import Traveller 

352 

353 return Traveller(DateTime) 

354 

355 def freeze(*args, **kwargs) -> Traveller: 

356 return _traveller().freeze(*args, **kwargs) 

357 

358 def travel(*args, **kwargs): 

359 return _traveller().travel(*args, **kwargs) 

360 

361 def travel_to(*args, **kwargs): 

362 return _traveller().travel_to(*args, **kwargs) 

363 

364 def travel_back(*args, **kwargs): 

365 return _traveller().travel_back(*args, **kwargs) 

366 

367 

368def __getattr__(name: str) -> Any: 

369 if name == "Traveller": 

370 # This wasn't in `__all__`, but it was defined before, so keep it for back compat 

371 from pendulum.testing.traveller import Traveller 

372 

373 return Traveller 

374 

375 if name == "__version__": 

376 import importlib.metadata 

377 import warnings 

378 

379 warnings.warn( 

380 "The '__version__' attribute is deprecated and will be removed in" 

381 " Pendulum 3.4. Use 'importlib.metadata.version(\"pendulum\")' instead.", 

382 DeprecationWarning, 

383 stacklevel=2, 

384 ) 

385 return importlib.metadata.version("pendulum") 

386 

387 raise AttributeError(name) 

388 

389 

390__all__ = [ 

391 "DAYS_PER_WEEK", 

392 "HOURS_PER_DAY", 

393 "MINUTES_PER_HOUR", 

394 "MONTHS_PER_YEAR", 

395 "SECONDS_PER_DAY", 

396 "SECONDS_PER_HOUR", 

397 "SECONDS_PER_MINUTE", 

398 "UTC", 

399 "WEEKS_PER_YEAR", 

400 "YEARS_PER_CENTURY", 

401 "YEARS_PER_DECADE", 

402 "Date", 

403 "DateTime", 

404 "Duration", 

405 "FixedTimezone", 

406 "Formatter", 

407 "Interval", 

408 "Time", 

409 "Timezone", 

410 "WeekDay", 

411 "date", 

412 "datetime", 

413 "duration", 

414 "format_diff", 

415 "freeze", 

416 "from_format", 

417 "from_timestamp", 

418 "get_locale", 

419 "instance", 

420 "interval", 

421 "local", 

422 "local_timezone", 

423 "locale", 

424 "naive", 

425 "now", 

426 "parse", 

427 "set_local_timezone", 

428 "set_locale", 

429 "test_local_timezone", 

430 "time", 

431 "timezone", 

432 "timezones", 

433 "today", 

434 "tomorrow", 

435 "travel", 

436 "travel_back", 

437 "travel_to", 

438 "week_ends_at", 

439 "week_starts_at", 

440 "yesterday", 

441]