Skip to content

Commit

Permalink
feat: add possibility to specify default timezone for datetimes wit…
Browse files Browse the repository at this point in the history
…hout `tzinfo` (#238)
  • Loading branch information
bednar authored May 5, 2021
1 parent be6760d commit bf1c1df
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 1 deletion.
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()

0 comments on commit bf1c1df

Please sign in to comment.