10000 feat: add possibility to specify default `timezone` for datetimes wit… · Remalloc/influxdb-client-python@bf1c1df · GitHub
[go: up one dir, main page]

Skip to content

Commit bf1c1df

Browse files
authored
feat: add possibility to specify default timezone for datetimes without tzinfo (influxdata#238)
1 parent be6760d commit bf1c1df

File tree

3 files changed

+34
-1
lines changed

3 files changed

+34
-1
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
### Features
44
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.
55
1. [#241](https://github.com/influxdata/influxdb-client-python/pull/241): Add detail error message for not supported type of `Point.field`
6+
1. [#238](https://github.com/influxdata/influxdb-client-python/pull/238): Add possibility to specify default `timezone` for datetimes without `tzinfo`
67

78
## 1.17.0 [2021-04-30]
89

influxdb_client/client/util/date_utils.py

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,15 @@
1010
class DateHelper:
1111
"""DateHelper to groups different implementations of date operations."""
1212

13+
def __init__(self, timezone: datetime.tzinfo = UTC) -> None:
14+
"""
15+
Initialize defaults.
16+
17+
:param timezone: Default timezone used for serialization "datetime" without "tzinfo".
18+
Default value is "UTC".
19+
"""
20+
self.timezone = timezone
21+
1322
def parse_date(self, date_string: str):
1423
"""
1524
Parse string into Date or Timestamp.
@@ -40,7 +49,7 @@ def to_utc(self, value: datetime):
4049
:return: datetime in UTC
4150
"""
4251
if not value.tzinfo:
43< EFD1 /code>-
return UTC.localize(value)
52+
return self.to_utc(value.replace(tzinfo=self.timezone))
4453
else:
4554
return value.astimezone(UTC)
4655

tests/test_DateHelper.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
# -*- coding: utf-8 -*-
2+
3+
import unittest
4+
from datetime import datetime, timezone
5+
6+
from pytz import UTC, timezone
7+
8+
from influxdb_client.client.util.date_utils import DateHelper
9+
10+
11+
class DateHelperTest(unittest.TestCase):
12+
13+
def test_to_utc(self):
14+
date = DateHelper().to_utc(datetime(2021, 4, 29, 20, 30, 10, 0))
15+
self.assertEqual(datetime(2021, 4, 29, 20, 30, 10, 0, UTC), date)
16+
17+
def test_to_utc_different_timezone(self):
18+
date = DateHelper(timezone=timezone('ETC/GMT+2')).to_utc(datetime(2021, 4, 29, 20, 30, 10, 0))
19+
self.assertEqual(datetime(2021, 4, 29, 22, 30, 10, 0, UTC), date)
20+
21+
22+
if __name__ == '__main__':
23+
unittest.main()

0 commit comments

Comments
 (0)
0