function isdatetime
Determines whether a given value (array or scalar) is a recognized datetime type, checking both NumPy datetime64 arrays and Python datetime objects.
/tf/active/vicechatdev/patches/util.py
894 - 903
simple
Purpose
This function provides a unified way to check if a value represents datetime data, handling both NumPy arrays (with datetime64 dtype or object dtype containing datetime objects) and scalar datetime values. It's useful for data validation and type checking in data processing pipelines that work with temporal data.
Source Code
def isdatetime(value):
"""
Whether the array or scalar is recognized datetime type.
"""
if isinstance(value, np.ndarray):
return (value.dtype.kind == "M" or
(value.dtype.kind == "O" and len(value) and
isinstance(value[0], datetime_types)))
else:
return isinstance(value, datetime_types)
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
value |
- | - | positional_or_keyword |
Parameter Details
value: The input to check for datetime type. Can be a NumPy array (with dtype 'M' for datetime64, or 'O' for object arrays containing datetime objects) or a scalar value that may be an instance of datetime_types (which likely includes datetime.datetime, datetime.date, datetime.time, and possibly pandas.Timestamp or other datetime-like objects)
Return Value
Returns a boolean value: True if the input is recognized as a datetime type (either a NumPy datetime64 array, an object array containing datetime objects, or a scalar datetime instance), False otherwise
Dependencies
numpy
Required Imports
import numpy as np
Usage Example
import numpy as np
import datetime
from datetime import datetime as dt_class
# Define datetime_types (normally defined in module scope)
datetime_types = (dt_class, datetime.date, datetime.time)
# Check scalar datetime
value1 = dt_class.now()
result1 = isdatetime(value1) # Returns: True
# Check NumPy datetime64 array
value2 = np.array(['2023-01-01', '2023-01-02'], dtype='datetime64')
result2 = isdatetime(value2) # Returns: True
# Check object array with datetime objects
value3 = np.array([dt_class(2023, 1, 1), dt_class(2023, 1, 2)], dtype=object)
result3 = isdatetime(value3) # Returns: True
# Check non-datetime value
value4 = np.array([1, 2, 3])
result4 = isdatetime(value4) # Returns: False
Best Practices
- Ensure 'datetime_types' is properly defined in the module scope before using this function
- Be aware that for object arrays, the function only checks the first element (value[0]) to determine if it contains datetime objects, which assumes homogeneous arrays
- The function checks for non-empty arrays before accessing value[0] to avoid IndexError
- For NumPy arrays, dtype.kind == 'M' checks for datetime64 dtype, while dtype.kind == 'O' checks for object dtype
- This function does not validate that all elements in an object array are datetime types, only the first element
Tags
Similar Components
AI-powered semantic similarity - components with related functionality: