2011-11-18 21:01:06 +08:00
|
|
|
"""Functions to parse datetime objects."""
|
|
|
|
|
|
|
|
# We're using regular expressions rather than time.strptime because:
|
2011-12-17 10:31:34 +08:00
|
|
|
# - They provide both validation and parsing.
|
|
|
|
# - They're more flexible for datetimes.
|
|
|
|
# - The date/datetime/time constructors produce friendlier error messages.
|
2011-11-18 21:01:06 +08:00
|
|
|
|
|
|
|
import datetime
|
2013-09-08 16:43:33 +08:00
|
|
|
|
2019-10-26 22:42:32 +08:00
|
|
|
from django.utils.regex_helper import _lazy_re_compile
|
2022-03-23 19:15:36 +08:00
|
|
|
from django.utils.timezone import get_fixed_timezone
|
2011-11-18 21:01:06 +08:00
|
|
|
|
2011-12-17 10:31:34 +08:00
|
|
|
date_re = _lazy_re_compile(r"(?P<year>\d{4})-(?P<month>\d{1,2})-(?P<day>\d{1,2})$")
|
2011-11-18 21:01:06 +08:00
|
|
|
|
2019-10-26 22:42:32 +08:00
|
|
|
time_re = _lazy_re_compile(
|
2012-08-20 03:47:41 +08:00
|
|
|
r"(?P<hour>\d{1,2}):(?P<minute>\d{1,2})"
|
2021-07-07 15:21:12 +08:00
|
|
|
r"(?::(?P<second>\d{1,2})(?:[\.,](?P<microsecond>\d{1,6})\d{0,6})?)?$"
|
2011-11-18 21:01:06 +08:00
|
|
|
)
|
|
|
|
|
2019-10-26 22:42:32 +08:00
|
|
|
datetime_re = _lazy_re_compile(
|
2012-08-20 03:47:41 +08:00
|
|
|
r"(?P<year>\d{4})-(?P<month>\d{1,2})-(?P<day>\d{1,2})"
|
|
|
|
r"[T ](?P<hour>\d{1,2}):(?P<minute>\d{1,2})"
|
2019-09-26 04:17:22 +08:00
|
|
|
r"(?::(?P<second>\d{1,2})(?:[\.,](?P<microsecond>\d{1,6})\d{0,6})?)?"
|
2021-05-08 08:59:17 +08:00
|
|
|
r"\s*(?P<tzinfo>Z|[+-]\d{2}(?::?\d{2})?)?$"
|
2011-11-18 21:01:06 +08:00
|
|
|
)
|
|
|
|
|
2019-10-26 22:42:32 +08:00
|
|
|
standard_duration_re = _lazy_re_compile(
|
2014-07-24 20:57:24 +08:00
|
|
|
r"^"
|
2015-06-02 17:08:41 +08:00
|
|
|
r"(?:(?P<days>-?\d+) (days?, )?)?"
|
2019-02-16 15:43:42 +08:00
|
|
|
r"(?P<sign>-?)"
|
|
|
|
r"((?:(?P<hours>\d+):)(?=\d+:\d+))?"
|
|
|
|
r"(?:(?P<minutes>\d+):)?"
|
|
|
|
r"(?P<seconds>\d+)"
|
2019-09-26 04:17:22 +08:00
|
|
|
r"(?:[\.,](?P<microseconds>\d{1,6})\d{0,6})?"
|
2014-07-24 20:57:24 +08:00
|
|
|
r"$"
|
|
|
|
)
|
|
|
|
|
|
|
|
# Support the sections of ISO 8601 date representation that are accepted by
|
|
|
|
# timedelta
|
2019-10-26 22:42:32 +08:00
|
|
|
iso8601_duration_re = _lazy_re_compile(
|
2016-05-26 20:48:36 +08:00
|
|
|
r"^(?P<sign>[-+]?)"
|
|
|
|
r"P"
|
2021-12-16 00:56:04 +08:00
|
|
|
r"(?:(?P<days>\d+([\.,]\d+)?)D)?"
|
2014-07-24 20:57:24 +08:00
|
|
|
r"(?:T"
|
2021-12-16 00:56:04 +08:00
|
|
|
r"(?:(?P<hours>\d+([\.,]\d+)?)H)?"
|
|
|
|
r"(?:(?P<minutes>\d+([\.,]\d+)?)M)?"
|
|
|
|
r"(?:(?P<seconds>\d+([\.,]\d+)?)S)?"
|
2014-07-24 20:57:24 +08:00
|
|
|
r")?"
|
|
|
|
r"$"
|
|
|
|
)
|
|
|
|
|
2017-04-13 10:03:35 +08:00
|
|
|
# Support PostgreSQL's day-time interval format, e.g. "3 days 04:05:06". The
|
|
|
|
# year-month and mixed intervals cannot be converted to a timedelta and thus
|
|
|
|
# aren't accepted.
|
2019-10-26 22:42:32 +08:00
|
|
|
postgres_interval_re = _lazy_re_compile(
|
2017-04-13 10:03:35 +08:00
|
|
|
r"^"
|
|
|
|
r"(?:(?P<days>-?\d+) (days? ?))?"
|
|
|
|
r"(?:(?P<sign>[-+])?"
|
|
|
|
r"(?P<hours>\d+):"
|
|
|
|
r"(?P<minutes>\d\d):"
|
|
|
|
r"(?P<seconds>\d\d)"
|
|
|
|
r"(?:\.(?P<microseconds>\d{1,6}))?"
|
|
|
|
r")?$"
|
|
|
|
)
|
|
|
|
|
2013-09-08 16:43:33 +08:00
|
|
|
|
2011-11-18 21:01:06 +08:00
|
|
|
def parse_date(value):
|
2017-01-25 04:32:33 +08:00
|
|
|
"""Parse a string and return a datetime.date.
|
2011-11-18 21:01:06 +08:00
|
|
|
|
2017-01-25 04:32:33 +08:00
|
|
|
Raise ValueError if the input is well formatted but not a valid date.
|
|
|
|
Return None if the input isn't well formatted.
|
2011-11-18 21:01:06 +08:00
|
|
|
"""
|
2021-07-01 19:05:41 +08:00
|
|
|
try:
|
|
|
|
return datetime.date.fromisoformat(value)
|
|
|
|
except ValueError:
|
|
|
|
if match := date_re.match(value):
|
|
|
|
kw = {k: int(v) for k, v in match.groupdict().items()}
|
|
|
|
return datetime.date(**kw)
|
2011-11-18 21:01:06 +08:00
|
|
|
|
2013-11-03 07:53:29 +08:00
|
|
|
|
2011-11-18 21:01:06 +08:00
|
|
|
def parse_time(value):
|
2017-01-25 04:32:33 +08:00
|
|
|
"""Parse a string and return a datetime.time.
|
2011-11-18 21:01:06 +08:00
|
|
|
|
|
|
|
This function doesn't support time zone offsets.
|
|
|
|
|
2017-01-25 04:32:33 +08:00
|
|
|
Raise ValueError if the input is well formatted but not a valid time.
|
|
|
|
Return None if the input isn't well formatted, in particular if it
|
2011-11-18 21:01:06 +08:00
|
|
|
contains an offset.
|
|
|
|
"""
|
2021-07-01 19:05:41 +08:00
|
|
|
try:
|
|
|
|
# The fromisoformat() method takes time zone info into account and
|
|
|
|
# returns a time with a tzinfo component, if possible. However, there
|
|
|
|
# are no circumstances where aware datetime.time objects make sense, so
|
|
|
|
# remove the time zone offset.
|
|
|
|
return datetime.time.fromisoformat(value).replace(tzinfo=None)
|
|
|
|
except ValueError:
|
|
|
|
if match := time_re.match(value):
|
|
|
|
kw = match.groupdict()
|
|
|
|
kw["microsecond"] = kw["microsecond"] and kw["microsecond"].ljust(6, "0")
|
|
|
|
kw = {k: int(v) for k, v in kw.items() if v is not None}
|
|
|
|
return datetime.time(**kw)
|
2011-11-18 21:01:06 +08:00
|
|
|
|
2013-11-03 07:53:29 +08:00
|
|
|
|
2011-11-18 21:01:06 +08:00
|
|
|
def parse_datetime(value):
|
2017-01-25 04:32:33 +08:00
|
|
|
"""Parse a string and return a datetime.datetime.
|
2011-11-18 21:01:06 +08:00
|
|
|
|
|
|
|
This function supports time zone offsets. When the input contains one,
|
2013-09-08 16:43:33 +08:00
|
|
|
the output uses a timezone with a fixed offset from UTC.
|
2011-11-18 21:01:06 +08:00
|
|
|
|
2017-01-25 04:32:33 +08:00
|
|
|
Raise ValueError if the input is well formatted but not a valid datetime.
|
|
|
|
Return None if the input isn't well formatted.
|
2011-11-18 21:01:06 +08:00
|
|
|
"""
|
2021-07-01 19:05:41 +08:00
|
|
|
try:
|
|
|
|
return datetime.datetime.fromisoformat(value)
|
|
|
|
except ValueError:
|
|
|
|
if match := datetime_re.match(value):
|
|
|
|
kw = match.groupdict()
|
|
|
|
kw["microsecond"] = kw["microsecond"] and kw["microsecond"].ljust(6, "0")
|
|
|
|
tzinfo = kw.pop("tzinfo")
|
|
|
|
if tzinfo == "Z":
|
2022-03-23 19:15:36 +08:00
|
|
|
tzinfo = datetime.timezone.utc
|
2021-07-01 19:05:41 +08:00
|
|
|
elif tzinfo is not None:
|
|
|
|
offset_mins = int(tzinfo[-2:]) if len(tzinfo) > 3 else 0
|
|
|
|
offset = 60 * int(tzinfo[1:3]) + offset_mins
|
|
|
|
if tzinfo[0] == "-":
|
|
|
|
offset = -offset
|
|
|
|
tzinfo = get_fixed_timezone(offset)
|
|
|
|
kw = {k: int(v) for k, v in kw.items() if v is not None}
|
|
|
|
return datetime.datetime(**kw, tzinfo=tzinfo)
|
2014-07-24 20:57:24 +08:00
|
|
|
|
|
|
|
|
|
|
|
def parse_duration(value):
|
2017-01-25 04:32:33 +08:00
|
|
|
"""Parse a duration string and return a datetime.timedelta.
|
2014-07-24 20:57:24 +08:00
|
|
|
|
|
|
|
The preferred format for durations in Django is '%d %H:%M:%S.%f'.
|
|
|
|
|
2017-04-13 10:03:35 +08:00
|
|
|
Also supports ISO 8601 representation and PostgreSQL's day-time interval
|
|
|
|
format.
|
2014-07-24 20:57:24 +08:00
|
|
|
"""
|
2017-11-06 23:23:29 +08:00
|
|
|
match = (
|
|
|
|
standard_duration_re.match(value)
|
|
|
|
or iso8601_duration_re.match(value)
|
|
|
|
or postgres_interval_re.match(value)
|
|
|
|
)
|
2014-07-24 20:57:24 +08:00
|
|
|
if match:
|
|
|
|
kw = match.groupdict()
|
2016-05-26 20:48:36 +08:00
|
|
|
sign = -1 if kw.pop("sign", "+") == "-" else 1
|
2014-07-24 20:57:24 +08:00
|
|
|
if kw.get("microseconds"):
|
|
|
|
kw["microseconds"] = kw["microseconds"].ljust(6, "0")
|
2019-11-27 15:14:00 +08:00
|
|
|
kw = {k: float(v.replace(",", ".")) for k, v in kw.items() if v is not None}
|
|
|
|
days = datetime.timedelta(kw.pop("days", 0.0) or 0.0)
|
2020-12-19 17:53:35 +08:00
|
|
|
if match.re == iso8601_duration_re:
|
|
|
|
days *= sign
|
2017-04-13 10:03:35 +08:00
|
|
|
return days + sign * datetime.timedelta(**kw)
|