### parse with as_timedelta - Return timedelta/relativedelta Objects Source: https://context7.com/onegreyonewhite/pytimeparse2/llms.txt When `as_timedelta=True`, the function returns a `dateutil.relativedelta.relativedelta` object (if python-dateutil is installed) or `datetime.timedelta` object instead of seconds. This preserves the original time units and enables precise date arithmetic. ```APIDOC ## parse with as_timedelta - Return timedelta/relativedelta Objects ### Description When `as_timedelta=True`, the function returns a `dateutil.relativedelta.relativedelta` object (if python-dateutil is installed) or `datetime.timedelta` object instead of seconds. This preserves the original time units and enables precise date arithmetic. ### Method `parse(time_str: str, granularity: str = 'seconds', as_timedelta: bool = False) -> Union[int, float, timedelta, relativedelta, None]` ### Endpoint `pytimeparse2.parse()` ### Parameters #### Path Parameters None #### Query Parameters - **as_timedelta** (bool) - Optional - If `True`, returns a `relativedelta` or `timedelta` object instead of seconds. #### Request Body None ### Request Example ```python from pytimeparse2 import parse from datetime import datetime # Returns relativedelta with original units preserved print(parse('24h', as_timedelta=True)) print(parse('2h32m', as_timedelta=True)) print(parse('1w3d2h32m', as_timedelta=True)) print(parse('1y2mo3w4d5h6m7s8ms', as_timedelta=True)) # Signed timedeltas print(parse('-2 days', as_timedelta=True)) # Use for date arithmetic delta = parse('2 weeks 3 days', as_timedelta=True) future_date = datetime.now() + delta print(f"Date in 2 weeks 3 days: {future_date}") # Milliseconds converted to microseconds print(parse('500ms', as_timedelta=True)) ``` ### Response #### Success Response (200) - **timedelta_object** (`datetime.timedelta` | `dateutil.relativedelta.relativedelta`) - A timedelta or relativedelta object representing the parsed time. #### Response Example ```json { "timedelta_object": "relativedelta(days=+1)" } ``` ``` -------------------------------- ### Parse Time Strings with Granularity and Timedelta Source: https://context7.com/onegreyonewhite/pytimeparse2/llms.txt Demonstrates parsing time strings with specified granularity (e.g., 'minutes') and converting the output to `relativedelta` or `timedelta` objects. This is useful for handling time expressions with different levels of precision. ```python from pytimeparse2 import parse from dateutil.relativedelta import relativedelta # Example with granularity result_granularity = parse('4:30', granularity='minutes', as_timedelta=True) print(result_granularity) # Output: relativedelta(hours=+4, minutes=+30) # Example with microseconds result_microseconds = parse('0.5', as_timedelta=True) print(result_microseconds) # Output: relativedelta(microseconds=+500000) ``` -------------------------------- ### Parse time expressions into timedelta objects Source: https://github.com/onegreyonewhite/pytimeparse2/blob/master/README.rst Shows how to use the as_timedelta parameter to return a datetime.timedelta or dateutil.relativedelta object instead of a raw integer. ```python from pytimeparse2 import parse parse('24h', as_timedelta=True) ``` -------------------------------- ### Return Timedelta Objects Source: https://context7.com/onegreyonewhite/pytimeparse2/llms.txt Demonstrates how to return dateutil.relativedelta or datetime.timedelta objects instead of raw seconds, which is useful for performing date arithmetic. ```python from pytimeparse2 import parse from datetime import datetime # Returns relativedelta with original units preserved print(parse('24h', as_timedelta=True)) # Output: relativedelta(days=+1) print(parse('2h32m', as_timedelta=True)) # Output: relativedelta(hours=+2, minutes=+32) print(parse('1w3d2h32m', as_timedelta=True)) # Output: relativedelta(weeks=+1, days=+3, hours=+2, minutes=+32) print(parse('1y2mo3w4d5h6m7s8ms', as_timedelta=True)) # Output: relativedelta(years=+1, months=+2, weeks=+3, days=+4, hours=+5, minutes=+6, seconds=+7, microseconds=+8000) # Signed timedeltas print(parse('-2 days', as_timedelta=True)) # Output: relativedelta(days=-2) # Use for date arithmetic delta = parse('2 weeks 3 days', as_timedelta=True) future_date = datetime.now() + delta print(f"Date in 2 weeks 3 days: {future_date}") # Milliseconds converted to microseconds print(parse('500ms', as_timedelta=True)) ``` -------------------------------- ### Parse time expressions into seconds Source: https://github.com/onegreyonewhite/pytimeparse2/blob/master/README.rst Demonstrates how to import the parse function and convert a human-readable time string into an integer or float representing the total number of seconds. ```python from pytimeparse2 import parse parse('1.2 minutes') ``` -------------------------------- ### Convert seconds back to string format Source: https://github.com/onegreyonewhite/pytimeparse2/blob/master/README.rst Illustrates how to use the standard library's datetime module to format a parsed integer of seconds back into a human-readable string representation. ```python from pytimeparse2 import parse import datetime seconds = parse('1 day, 14:20:16') str(datetime.timedelta(seconds=seconds)) ``` -------------------------------- ### Control dateutil Support with disable_dateutil/enable_dateutil Source: https://context7.com/onegreyonewhite/pytimeparse2/llms.txt Demonstrates how to toggle the use of the `python-dateutil` library for `relativedelta` object generation. Disabling `dateutil` causes `as_timedelta=True` to return standard `datetime.timedelta` objects, which is useful for avoiding dependencies or ensuring consistent output types. ```python from pytimeparse2 import parse, disable_dateutil, enable_dateutil from datetime import timedelta # Default behavior (dateutil enabled if installed) result_default = parse('10:10', as_timedelta=True) print(type(result_default).__name__) # Output: relativedelta # Disable dateutil support disable_dateutil() # Now returns standard timedelta result_timedelta = parse('10:10', as_timedelta=True) print(type(result_timedelta).__name__) # Output: timedelta print(result_timedelta) # Output: 0:10:10 result_hours_minutes = parse('2h30m', as_timedelta=True) print(type(result_hours_minutes)) # Output: print(result_hours_minutes) # Output: 2:30:00 # Re-enable dateutil support enable_dateutil() result_relativedelta = parse('10:10', as_timedelta=True) print(type(result_relativedelta).__name__) # Output: relativedelta # Note on years and months conversion disable_dateutil() print(parse('1 month')) # Output: 2592000 (30 * 24 * 60 * 60) enable_dateutil() print(parse('1 month', as_timedelta=True)) # Output: relativedelta(months=+1) ``` -------------------------------- ### Convert Seconds Back to Readable Time Strings Source: https://context7.com/onegreyonewhite/pytimeparse2/llms.txt Shows how to convert the seconds output from `pytimeparse2` back into a human-readable time format using Python's `datetime.timedelta`. This enables a complete round-trip conversion for displaying parsed time durations. ```python import datetime from pytimeparse2 import parse # Parse time expression to seconds seconds_parsed = parse('1 day, 14:20:16') print(f"Parsed seconds: {seconds_parsed}") # Output: 138016 # Convert seconds back to readable string readable_time = str(datetime.timedelta(seconds=seconds_parsed)) print(f"Readable: {readable_time}") # Output: 1 day, 14:20:16 # Round-trip conversion example time_expressions = [ '2 days, 4:13:02', '5:34:56', '1:30:00', ] for expr in time_expressions: secs = parse(expr) back = str(datetime.timedelta(seconds=secs)) print(f"'{expr}' -> {secs} seconds -> '{back}'") # Output: # '2 days, 4:13:02' -> 187982 seconds -> '2 days, 4:13:02' # '5:34:56' -> 20096 seconds -> '5:34:56' # '1:30:00' -> 5400 seconds -> '1:30:00' # Custom formatting for display def format_duration(seconds): td = datetime.timedelta(seconds=abs(seconds)) sign = '-' if seconds < 0 else '' return f"{sign}{td}" print(format_duration(parse('-2h30m'))) print(format_duration(parse('48h'))) ``` -------------------------------- ### Handle Ambiguous Colon Times with Granularity Source: https://context7.com/onegreyonewhite/pytimeparse2/llms.txt Shows how to use the granularity parameter to resolve ambiguity in colon-separated time strings, such as interpreting '1:30' as minutes/seconds versus hours/minutes. ```python from pytimeparse2 import parse # Default granularity='seconds': 1:30 means 1 min 30 sec print(parse('1:30')) # Output: 90 print(parse('4:32')) # Output: 272 # With granularity='minutes': 1:30 means 1 hr 30 min print(parse('1:30', granularity='minutes')) # Output: 5400 print(parse('4:32', granularity='minutes')) # Output: 16320 # Granularity doesn't affect unambiguous formats print(parse('4:32:02', granularity='minutes')) # Output: 16322 (still hr:min:sec) print(parse('7:02.223', granularity='minutes')) # Output: 422.223 (fractional sec) # Useful for parsing user input where format is known user_input = '2:45' # User means 2 hours 45 minutes seconds = parse(user_input, granularity='minutes') print(f"{user_input} = {seconds} seconds") # Output: 2:45 = 9900 seconds ``` -------------------------------- ### Dateutil Support Control Source: https://github.com/onegreyonewhite/pytimeparse2/blob/master/README.rst Control whether the library uses `dateutil.relativedelta` for timedelta conversions. ```APIDOC ## Dateutil Support Control ### Description Manages the integration with the `dateutil` library for more advanced timedelta representations. ### Methods - `disable_dateutil()`: Forces the library to not use `dateutil` for parsing, even if installed. - `enable_dateutil()`: Enables the use of `dateutil` for parsing, if installed. ### Usage Example ```python from pytimeparse2 import parse, disable_dateutil, enable_dateutil # Example with dateutil enabled (default if installed) timedelta_enabled = parse('24h', as_timedelta=True) print(timedelta_enabled) # Disable dateutil disable_dateutil() timedelta_disabled = parse('24h', as_timedelta=True) print(timedelta_disabled) # Re-enable dateutil enable_dateutil() timedelta_reenabled = parse('24h', as_timedelta=True) print(timedelta_reenabled) ``` ### Response These functions do not return a value but modify the internal behavior of the `parse` function. ``` -------------------------------- ### Parse Time Expression to Seconds Source: https://context7.com/onegreyonewhite/pytimeparse2/llms.txt Demonstrates the primary parse function to convert various string formats into integer or float seconds. It handles compact notation, colon-separated times, verbose English, and signed expressions. ```python from pytimeparse2 import parse # Basic compact notation print(parse('32m')) # Output: 1920 print(parse('2h32m')) # Output: 9120 print(parse('3d2h32m')) # Output: 268320 print(parse('1w3d2h32m')) # Output: 873120 # Colon-separated time formats print(parse('4:13')) # Output: 253 (4 min 13 sec) print(parse('4:13:02')) # Output: 15182 (4 hr 13 min 2 sec) print(parse(':22')) # Output: 22 (bare seconds) print(parse('2:04:13:02.266')) # Output: 187982.266 (days:hr:min:sec) # Verbose English expressions print(parse('5 hours, 34 minutes, 56 seconds')) # Output: 20096 print(parse('2 days, 5 hours, 34 minutes')) # Output: 192840 print(parse('1.2 minutes')) # Output: 72 # Years and months (uses 365 days/year, 30 days/month) print(parse('3y')) # Output: 94608000 print(parse('2 months')) # Output: 5184000 print(parse('1y2mo3w4d5h6m7s8ms')) # Output: 38898367.008 # Milliseconds print(parse('500ms')) # Output: 0.5 print(parse('3 milliseconds')) # Output: 0.003 # Signed time expressions print(parse('+1 hour')) # Output: 3600 print(parse('-30 minutes')) # Output: -1800 print(parse('- 2h 30m')) # Output: -9000 # Numeric passthrough print(parse(100)) # Output: 100 print(parse('99.5')) # Output: 99.5 # Invalid input returns None print(parse('invalid')) # Output: None ``` -------------------------------- ### Enable Error Handling with raise_exception in pytimeparse2 Source: https://context7.com/onegreyonewhite/pytimeparse2/llms.txt Explains how to enable explicit error handling for invalid time string inputs using the `raise_exception=True` parameter. By default, `parse()` returns `None` for invalid inputs, but setting this to `True` will raise a `ValueError`, allowing for more robust application logic. ```python from pytimeparse2 import parse # Default behavior: invalid input returns None result_none = parse('invalid time string') print(result_none) # Output: None # With raise_exception=True: raises ValueError try: parse(':1.1.1', raise_exception=True) except ValueError as e: print(f"Parsing error: {e}") # Output: Parsing error: could not convert string to float: ':1.1.1' # Function to validate user input with exception handling def parse_duration(user_input): try: seconds = parse(user_input, raise_exception=True) return seconds except ValueError: raise ValueError(f"Invalid duration format: {user_input}") # Valid input print(parse_duration('2 hours')) # Output: 7200 # Invalid input raises exception try: parse_duration('not a time') except ValueError as e: print(e) # Output: Invalid duration format: not a time ``` -------------------------------- ### Parse Time Expression Source: https://github.com/onegreyonewhite/pytimeparse2/blob/master/README.rst The `pytimeparse2.parse` function converts human-readable time strings into a numerical representation of seconds or a timedelta object. ```APIDOC ## Parse Time Expression ### Description Parses a string representing a duration into seconds or a `datetime.timedelta` object. ### Method `parse(time_string, as_timedelta=False)` ### Parameters #### Path Parameters None #### Query Parameters - **time_string** (string) - Required - The string to parse (e.g., "32m", "2h32m", "1w 3d 2h 32m", "4:13:02.266"). - **as_timedelta** (boolean) - Optional - If `True`, returns a `datetime.timedelta` or `dateutil.relativedelta.relativedelta` object. Defaults to `False`. ### Request Example ```python from pytimeparse2 import parse # Parse to seconds seconds = parse('1.2 minutes') print(seconds) # Output: 72 # Parse to timedelta timedelta = parse('24h', as_timedelta=True) print(timedelta) # Output: relativedelta(days=+1) ``` ### Response #### Success Response (200) - **seconds** (integer or float) - The duration in seconds. - **timedelta** (`datetime.timedelta` or `dateutil.relativedelta.relativedelta`) - The duration as a timedelta object, if `as_timedelta=True`. #### Response Example ```json { "seconds": 72 } ``` ```json { "timedelta": "relativedelta(days=+1)" } ``` ``` -------------------------------- ### parse with granularity - Handle Ambiguous Colon Times Source: https://context7.com/onegreyonewhite/pytimeparse2/llms.txt The `granularity` parameter controls how ambiguous colon-separated times like `1:30` are interpreted. By default, `1:30` means 1 minute 30 seconds. With `granularity='minutes'`, it's interpreted as 1 hour 30 minutes. ```APIDOC ## parse with granularity - Handle Ambiguous Colon Times ### Description The `granularity` parameter controls how ambiguous colon-separated times like `1:30` are interpreted. By default, `1:30` means 1 minute 30 seconds. With `granularity='minutes'`, it's interpreted as 1 hour 30 minutes. ### Method `parse(time_str: str, granularity: str = 'seconds', as_timedelta: bool = False) -> Union[int, float, timedelta, relativedelta, None]` ### Endpoint `pytimeparse2.parse()` ### Parameters #### Path Parameters None #### Query Parameters - **granularity** (str) - Optional - Specifies the base unit for parsing ambiguous colon-separated times. Can be 'seconds' (default) or 'minutes'. #### Request Body None ### Request Example ```python from pytimeparse2 import parse # Default granularity='seconds': 1:30 means 1 min 30 sec print(parse('1:30')) print(parse('4:32')) # With granularity='minutes': 1:30 means 1 hr 30 min print(parse('1:30', granularity='minutes')) print(parse('4:32', granularity='minutes')) # Granularity doesn't affect unambiguous formats print(parse('4:32:02', granularity='minutes')) print(parse('7:02.223', granularity='minutes')) # Useful for parsing user input where format is known user_input = '2:45' # User means 2 hours 45 minutes seconds = parse(user_input, granularity='minutes') print(f"{user_input} = {seconds} seconds") ``` ### Response #### Success Response (200) - **seconds** (int | float) - The equivalent number of seconds, interpreted based on the specified granularity. #### Response Example ```json { "seconds": 5400 } ``` ``` -------------------------------- ### parse - Parse Time Expression to Seconds Source: https://context7.com/onegreyonewhite/pytimeparse2/llms.txt The main function that parses a time expression string and returns the equivalent number of seconds. Supports multiple input formats including compact notation, colon-separated times, verbose English expressions, and numeric values. Returns `int` when possible, `float` for fractional seconds, or `None` if parsing fails. ```APIDOC ## parse - Parse Time Expression to Seconds ### Description The main function that parses a time expression string and returns the equivalent number of seconds. Supports multiple input formats including compact notation, colon-separated times, verbose English expressions, and numeric values. Returns `int` when possible, `float` for fractional seconds, or `None` if parsing fails. ### Method `parse(time_str: str, granularity: str = 'seconds', as_timedelta: bool = False) -> Union[int, float, timedelta, relativedelta, None]` ### Endpoint `pytimeparse2.parse()` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from pytimeparse2 import parse # Basic compact notation print(parse('32m')) print(parse('2h32m')) print(parse('3d2h32m')) print(parse('1w3d2h32m')) # Colon-separated time formats print(parse('4:13')) print(parse('4:13:02')) print(parse(':22')) print(parse('2:04:13:02.266')) # Verbose English expressions print(parse('5 hours, 34 minutes, 56 seconds')) print(parse('2 days, 5 hours, 34 minutes')) print(parse('1.2 minutes')) # Years and months (uses 365 days/year, 30 days/month) print(parse('3y')) print(parse('2 months')) print(parse('1y2mo3w4d5h6m7s8ms')) # Milliseconds print(parse('500ms')) print(parse('3 milliseconds')) # Signed time expressions print(parse('+1 hour')) print(parse('-30 minutes')) print(parse('- 2h 30m')) # Numeric passthrough print(parse(100)) print(parse('99.5')) # Invalid input returns None print(parse('invalid')) ``` ### Response #### Success Response (200) - **seconds** (int | float) - The equivalent number of seconds. - **None** - If parsing fails. #### Response Example ```json { "seconds": 1920 } ``` #### Error Response - **None** - Returned when the input string cannot be parsed. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.