🔍 Code Extractor

function parse_datetime_v2

Maturity: 25

Parses a datetime string by normalizing fractional seconds and timezone format, then converts it to a datetime object using ISO format parsing.

File:
/tf/active/vicechatdev/rmcl/utils.py
Lines:
10 - 15
Complexity:
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

  • datetime
  • re

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.

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function parse_datetime_v1 71.8% similar

    Converts various date representations (string, integer, pandas Timestamp) into a numpy datetime64 object using pandas datetime parsing capabilities.

    From: /tf/active/vicechatdev/patches/util.py
  • function format_datetime_v1 71.2% similar

    Converts an ISO format datetime string into a human-readable UTC datetime string formatted as 'YYYY-MM-DD HH:MM:SS UTC'.

    From: /tf/active/vicechatdev/SPFCsync/dry_run_test.py
  • function parse_datetime_selection 65.1% similar

    Converts string or datetime-like selection specifications into parsed datetime objects, handling single values, slices, and collections.

    From: /tf/active/vicechatdev/patches/util.py
  • function parse_datetime 65.0% similar

    Parses a datetime string in YYYY-MM-DD HH:MM:SS format into a Python datetime object, returning None if parsing fails.

    From: /tf/active/vicechatdev/CDocs/utils/__init__.py
  • function dt_to_int 58.1% similar

    Converts various datetime types (pandas, numpy, cftime, Python datetime) to an integer timestamp with a specified time unit.

    From: /tf/active/vicechatdev/patches/util.py
← Back to Browse