Don't raise errors when using datetime objects in as_datetime
Jinja function/filter (#109062)
* add support for datetime objects to as_datetime * change import of datetime.date --------- Co-authored-by: Erik Montnemery <erik@montnemery.com>
This commit is contained in:
parent
3d59303433
commit
e90d76b18d
2 changed files with 39 additions and 4 deletions
|
@ -9,7 +9,7 @@ import collections.abc
|
|||
from collections.abc import Callable, Generator, Iterable
|
||||
from contextlib import AbstractContextManager, suppress
|
||||
from contextvars import ContextVar
|
||||
from datetime import datetime, timedelta
|
||||
from datetime import date, datetime, time, timedelta
|
||||
from functools import cache, lru_cache, partial, wraps
|
||||
import json
|
||||
import logging
|
||||
|
@ -2001,12 +2001,12 @@ def square_root(value, default=_SENTINEL):
|
|||
def timestamp_custom(value, date_format=DATE_STR_FORMAT, local=True, default=_SENTINEL):
|
||||
"""Filter to convert given timestamp to format."""
|
||||
try:
|
||||
date = dt_util.utc_from_timestamp(value)
|
||||
result = dt_util.utc_from_timestamp(value)
|
||||
|
||||
if local:
|
||||
date = dt_util.as_local(date)
|
||||
result = dt_util.as_local(result)
|
||||
|
||||
return date.strftime(date_format)
|
||||
return result.strftime(date_format)
|
||||
except (ValueError, TypeError):
|
||||
# If timestamp can't be converted
|
||||
if default is _SENTINEL:
|
||||
|
@ -2048,6 +2048,12 @@ def forgiving_as_timestamp(value, default=_SENTINEL):
|
|||
|
||||
def as_datetime(value: Any, default: Any = _SENTINEL) -> Any:
|
||||
"""Filter and to convert a time string or UNIX timestamp to datetime object."""
|
||||
# Return datetime.datetime object without changes
|
||||
if type(value) is datetime:
|
||||
return value
|
||||
# Add midnight to datetime.date object
|
||||
if type(value) is date:
|
||||
return datetime.combine(value, time(0, 0, 0))
|
||||
try:
|
||||
# Check for a valid UNIX timestamp string, int or float
|
||||
timestamp = float(value)
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue