parse_timedelta¶
- safir.datetime.parse_timedelta(text)¶
Parse a string into a
datetime.timedelta
.Expects a string consisting of one or more sequences of numbers and duration abbreviations, separated by optional whitespace. Whitespace at the beginning and end of the string is ignored. The supported abbreviations are:
Week:
weeks
,week
,w
Day:
days
,day
,d
Hour:
hours
,hour
,hr
,h
Minute:
minutes
,minute
,mins
,min
,m
Second:
seconds
,second
,secs
,sec
,s
If several are present, they must be given in the above order. Example valid strings are
8d
(8 days),4h 3minutes
(four hours and three minutes), and5w4d
(five weeks and four days).This function can be as a before-mode validator for Pydantic
timedelta
fields, replacing Pydantic’s default ISO 8601 duration support.- Parameters:
text (
str
) – Input string.- Returns:
Converted
datetime.timedelta
.- Return type:
- Raises:
ValueError – Raised if the string is not in a valid format.
Examples
To accept a
timedelta
in this format in a Pydantic model, use a Pydantic field validator such as the following:@field_validator("lifetime", mode="before") @classmethod def _validate_lifetime( cls, v: str | float | timedelta ) -> float | timedelta: if not isinstance(v, str): return v return parse_timedelta(v)
This will disable the Pydantic support for ISO 8601 durations and expect the format parsed by this function instead.