dosubot[bot] commented on issue #29574:
URL: https://github.com/apache/superset/issues/29574#issuecomment-2225321843
<!-- Greeting -->
@mudasirmirza Hello! I'm here to assist you with any issues you're facing.
Let's work together to resolve the problem.
<!-- Answer -->
The error `'str' object has no attribute 'tzinfo'` occurs because the code
expects a datetime object with timezone information but encounters a string
instead. To resolve this, you need to ensure that datetime objects in your data
have the `tzinfo` attribute set correctly.
Here are the steps to fix this issue:
1. **Preprocess Data to Ensure Timezone Information**:
Convert string representations of datetime to actual datetime objects
with timezone information before they are processed. You can modify the data
preprocessing step as follows:
```python
from datetime import datetime
import pytz
def preprocess_data(data):
for row in data:
for i, value in enumerate(row):
if isinstance(value, str):
try:
# Attempt to parse the string as a datetime object
dt = datetime.fromisoformat(value)
# Add timezone information if missing
if dt.tzinfo is None:
dt = dt.replace(tzinfo=pytz.UTC)
row[i] = dt
except ValueError:
# If parsing fails, keep the original string
pass
return data
# Example usage
data = [
("2023-10-01T12:00:00", "some other value"),
("2023-10-02T13:00:00+00:00", "another value"),
]
preprocessed_data = preprocess_data(data)
```
2. **Ensure `convert_dttm` Method Handles Datetime Objects Correctly**:
The `convert_dttm` method in the `ElasticSearchEngineSpec` class should
convert datetime objects to the appropriate string format for Elasticsearch
queries. Here is the relevant implementation:
```python
class ElasticSearchEngineSpec(BaseEngineSpec): # pylint:
disable=abstract-method
engine = "elasticsearch"
engine_name = "ElasticSearch (SQL API)"
time_groupby_inline = True
allows_joins = False
allows_subqueries = True
allows_sql_comments = False
@classmethod
def convert_dttm(
cls, target_type: str, dttm: datetime, db_extra:
Optional[dict[str, Any]] = None
) -> Optional[str]:
db_extra = db_extra or {}
sqla_type = cls.get_sqla_column_type(target_type)
if isinstance(sqla_type, types.DateTime):
es_version = db_extra.get("version")
supports_dttm_parse = False
try:
if es_version:
supports_dttm_parse = Version(es_version) >=
Version("7.8")
except Exception as ex: # pylint: disable=broad-except
logger.error("Unexpected error while convert es_version",
exc_info=True)
logger.exception(ex)
if supports_dttm_parse:
datetime_formatted = dttm.isoformat(sep=" ",
timespec="seconds")
return (
f"""DATETIME_PARSE('{datetime_formatted}',
'yyyy-MM-dd HH:mm:ss')"""
)
return f"""CAST('{dttm.isoformat(timespec="seconds")}' AS
DATETIME)"""
return None
```
By ensuring that your datetime objects have the `tzinfo` attribute set and
are correctly formatted for Elasticsearch queries, you can avoid the `'str'
object has no attribute 'tzinfo'` error when querying an Elasticsearch data
source in Apache Superset
<sup>[[1]](https://github.com/apache/superset/blob/master/superset/result_set.py)</sup><sup>[[2]](https://github.com/apache/superset/blob/master/superset/db_engine_specs/elasticsearch.py)</sup>.
<!-- Dosu Comment Footer -->
*To continue talking to [Dosu](https://dosu.dev), mention @dosu.*
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]