Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add possibility to specify default timezone for datetimes without tzinfo #238

Merged
merged 3 commits into from
May 5, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
### Features
1. [#237](https://github.com/influxdata/influxdb-client-python/pull/237): Use kwargs to pass query parameters into API list call - useful for the ability to use pagination.
1. [#241](https://github.com/influxdata/influxdb-client-python/pull/241): Add detail error message for not supported type of `Point.field`
1. [#238](https://github.com/influxdata/influxdb-client-python/pull/238): Add possibility to specify default `timezone` for datetimes without `tzinfo`

## 1.17.0 [2021-04-30]

Expand Down
11 changes: 10 additions & 1 deletion influxdb_client/client/util/date_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,15 @@
class DateHelper:
"""DateHelper to groups different implementations of date operations."""

def __init__(self, timezone: datetime.tzinfo = UTC) -> None:
"""
Initialize defaults.

:param timezone: Default timezone used for serialization "datetime" without "tzinfo".
Default value is "UTC".
"""
self.timezone = timezone

def parse_date(self, date_string: str):
"""
Parse string into Date or Timestamp.
Expand Down Expand Up @@ -40,7 +49,7 @@ def to_utc(self, value: datetime):
:return: datetime in UTC
"""
if not value.tzinfo:
return UTC.localize(value)
return self.to_utc(value.replace(tzinfo=self.timezone))
else:
return value.astimezone(UTC)

Expand Down
23 changes: 23 additions & 0 deletions tests/test_DateHelper.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# -*- coding: utf-8 -*-

import unittest
from datetime import datetime, timezone

from pytz import UTC, timezone

from influxdb_client.client.util.date_utils import DateHelper


class DateHelperTest(unittest.TestCase):

def test_to_utc(self):
date = DateHelper().to_utc(datetime(2021, 4, 29, 20, 30, 10, 0))
self.assertEqual(datetime(2021, 4, 29, 20, 30, 10, 0, UTC), date)

def test_to_utc_different_timezone(self):
date = DateHelper(timezone=timezone('ETC/GMT+2')).to_utc(datetime(2021, 4, 29, 20, 30, 10, 0))
self.assertEqual(datetime(2021, 4, 29, 22, 30, 10, 0, UTC), date)


if __name__ == '__main__':
unittest.main()