Formats the given date. By default, we return a relative time (e.g., "2 minutes ago"). You can return an absolute date string with ``relative=False``. You can force a full format date ("July 10, 1980") with ``full_format=True``. This method is primarily int
(
self,
date: Union[int, float, datetime.datetime],
gmt_offset: int = 0,
relative: bool = True,
shorter: bool = False,
full_format: bool = False,
)
| 326 | raise NotImplementedError() |
| 327 | |
| 328 | def format_date( |
| 329 | self, |
| 330 | date: Union[int, float, datetime.datetime], |
| 331 | gmt_offset: int = 0, |
| 332 | relative: bool = True, |
| 333 | shorter: bool = False, |
| 334 | full_format: bool = False, |
| 335 | ) -> str: |
| 336 | """Formats the given date. |
| 337 | |
| 338 | By default, we return a relative time (e.g., "2 minutes ago"). You |
| 339 | can return an absolute date string with ``relative=False``. |
| 340 | |
| 341 | You can force a full format date ("July 10, 1980") with |
| 342 | ``full_format=True``. |
| 343 | |
| 344 | This method is primarily intended for dates in the past. |
| 345 | For dates in the future, we fall back to full format. |
| 346 | |
| 347 | .. versionchanged:: 6.4 |
| 348 | Aware `datetime.datetime` objects are now supported (naive |
| 349 | datetimes are still assumed to be UTC). |
| 350 | """ |
| 351 | if isinstance(date, (int, float)): |
| 352 | date = datetime.datetime.fromtimestamp(date, datetime.timezone.utc) |
| 353 | if date.tzinfo is None: |
| 354 | date = date.replace(tzinfo=datetime.timezone.utc) |
| 355 | now = datetime.datetime.now(datetime.timezone.utc) |
| 356 | if date > now: |
| 357 | if relative and (date - now).seconds < 60: |
| 358 | # Due to click skew, things are some things slightly |
| 359 | # in the future. Round timestamps in the immediate |
| 360 | # future down to now in relative mode. |
| 361 | date = now |
| 362 | else: |
| 363 | # Otherwise, future dates always use the full format. |
| 364 | full_format = True |
| 365 | local_date = date - datetime.timedelta(minutes=gmt_offset) |
| 366 | local_now = now - datetime.timedelta(minutes=gmt_offset) |
| 367 | local_yesterday = local_now - datetime.timedelta(hours=24) |
| 368 | difference = now - date |
| 369 | seconds = difference.seconds |
| 370 | days = difference.days |
| 371 | |
| 372 | _ = self.translate |
| 373 | format = None |
| 374 | if not full_format: |
| 375 | if relative and days == 0: |
| 376 | if seconds < 50: |
| 377 | return _("1 second ago", "%(seconds)d seconds ago", seconds) % { |
| 378 | "seconds": seconds |
| 379 | } |
| 380 | |
| 381 | if seconds < 50 * 60: |
| 382 | minutes = round(seconds / 60.0) |
| 383 | return _("1 minute ago", "%(minutes)d minutes ago", minutes) % { |
| 384 | "minutes": minutes |
| 385 | } |