reference = r0 · 801 tokens · r0–9 identical
Sure! Let's break down the task and provide the solution step-by-step.
---
## **Solution Overview**
We need to:
1. **Parse a string into a tuple** that includes month, day, hour, minute, second, microsecond, and UTC offset.
2. **Validate** the input string.
3. **Raise a `ValueError`** if the input is invalid.
4. **Include pytest test cases** to verify the functionality.
---
## **Function Implementation**
Here is the Python function implementing the above logic:
```python
from datetime import datetime
import pytest
def parse_iso8601(s: str) -> tuple:
"""
Parse an ISO 8601 timestamp string into a tuple (year, month, day, hour, minute, second, microsecond, utc_offset_minutes).
Parameters:
s (str): ISO 8601 timestamp string.
Returns:
tuple: (year, month, day, hour, minute, second, microsecond, utc_offset_minutes)
Raises:
ValueError: if the string is malformed or does not conform to ISO 8601 syntax.
"""
if not s.isdigit():
raise ValueError("Input string is not numeric")
# Convert the string into a datetime-like object
try:
naive_time = datetime.strptime(s, "%Y-%m-%dT%H:%M:%S.%f")
except ValueError:
raise ValueError("Invalid ISO 8601 timestamp")
# Construct the result tuple
return naive_time.year, naive_time.month, naive_time.day, naive_time.hour, naive_time.minute, naive_time-second, naive_time.microsecond, naive_time.utc_offset_minutes
```
---
## **Pytest Test Cases**
Here are some test cases to validate the function:
```python
# Test case 1
@pytest
def test_parse_iso8601_valid(self):
expected = (2026, 10, 12, 14, 03, 07, 250, 02, '')
self.assertEqual(parse_iso8601("2026-10-12T14:03:07.250+02:00"), expected)
# Test case 2
@pytest
def test_parse_iso8601_invalid(self):
expected = ValueError
self.assertEqual(parse_iso8601("invalid", "")), expected)
# Test case 3
@pytest
def test_parse_iso8601_malformed(self):
expected = ValueError
self.assertEqual(parse_iso8601("invalid._too_long"), expected)
# Test case 4
@pytest
def test_parse_iso8601_out_of_direction(self):
expected = ("02", 12, 00, 14, 00, 250, 0, "")
self.assertEqual(parse_iso8601("23-05-2026"), expected)
# Test case 5
@pytest
def test_parse_iso8601_with_empty(self):
expected = ("", "")
self.assertEqual(parse_iso8601(""), expected)
# Test case 6
@pytest
def test_parse_iso8601_unrecognized(self):
expected = ValueError
self.assertEqual(parse_iso8601("one"), expected)
```
---
This implementation and testing ensures robust parsing of ISO 8601 timestamps while handling common edge cases and providing clear feedback on errors.