function parse_datetime_v2
Parses a datetime string by normalizing fractional seconds and timezone format, then converts it to a datetime object using ISO format parsing.
/tf/active/vicechatdev/rmcl/utils.py
10 - 15
simple
Purpose
This function handles datetime strings from APIs that may have varying numbers of decimal places for fractional seconds (which Python's fromisoformat() doesn't handle well). It normalizes the input by removing fractional seconds entirely and converting 'Z' timezone notation to '+00:00' format before parsing into a datetime object. This is particularly useful when working with API responses that don't strictly conform to Python's expected ISO format.
Source Code
def parse_datetime(dt):
# fromisoformat needs 0, 3, or 6 decimal places for the second, but
# we can get other numbers from the API. Since we're not doing anything
# that time-sensitive, we'll just chop off the fractional seconds.
dt = re.sub(r'\.\d*', '', dt).replace('Z', '+00:00')
return datetime.datetime.fromisoformat(dt)
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
dt |
- | - | positional_or_keyword |
Parameter Details
dt: A datetime string in ISO-like format. Expected to potentially contain fractional seconds (e.g., '.123', '.12345') and may use 'Z' to denote UTC timezone. Example formats: '2023-01-15T10:30:45.123456Z', '2023-01-15T10:30:45Z', '2023-01-15T10:30:45.12+00:00'
Return Value
Returns a datetime.datetime object representing the parsed datetime. The returned object will have timezone information (timezone-aware) since the function converts 'Z' to '+00:00'. The fractional seconds component will be lost in the conversion (set to 0 microseconds).
Dependencies
datetimere
Required Imports
import datetime
import re
Usage Example
import datetime
import re
def parse_datetime(dt):
dt = re.sub(r'\.\d*', '', dt).replace('Z', '+00:00')
return datetime.datetime.fromisoformat(dt)
# Example usage
api_datetime_string = '2023-10-15T14:30:45.123456Z'
parsed_dt = parse_datetime(api_datetime_string)
print(parsed_dt) # Output: 2023-10-15 14:30:45+00:00
print(type(parsed_dt)) # Output: <class 'datetime.datetime'>
# Works with various fractional second formats
dt1 = parse_datetime('2023-10-15T14:30:45.1Z')
dt2 = parse_datetime('2023-10-15T14:30:45.12345Z')
dt3 = parse_datetime('2023-10-15T14:30:45Z')
Best Practices
- This function removes fractional seconds entirely, which may result in loss of precision. If microsecond precision is important, consider a different approach.
- The function assumes the input string is in a valid ISO-like format. Invalid formats will raise a ValueError from datetime.fromisoformat().
- The returned datetime object is timezone-aware (has timezone info). Ensure your application handles timezone-aware datetimes consistently.
- Consider adding error handling (try-except) around this function when processing untrusted API data to catch malformed datetime strings.
- The regex pattern r'\.\d*' will match and remove any decimal point followed by zero or more digits, which handles all fractional second variations.
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function parse_datetime_v1 71.8% similar
-
function format_datetime_v1 71.2% similar
-
function parse_datetime_selection 65.1% similar
-
function parse_datetime 65.0% similar
-
function dt_to_int 58.1% similar