|
5 | 5 | from unittest import TestCase
|
6 | 6 |
|
7 | 7 | import math
|
| 8 | +import pytz |
8 | 9 | from datetime import datetime as dt
|
9 | 10 | import datetime
|
10 | 11 | import numpy as np
|
@@ -88,6 +89,39 @@ def test_encode_as_numpy(self):
|
88 | 89 | res = utils.PlotlyJSONEncoder.encode_as_numpy(np.ma.core.masked)
|
89 | 90 | self.assertTrue(math.isnan(res))
|
90 | 91 |
|
| 92 | + def test_encode_as_datetime(self): |
| 93 | + |
| 94 | + # should *fail* without 'utcoffset' and 'isoformat' and '__sub__' attrs |
| 95 | + non_datetimes = [datetime.date(2013, 10, 1), 'noon', 56, '00:00:00'] |
| 96 | + for obj in non_datetimes: |
| 97 | + self.assertRaises(utils.NotEncodable, |
| 98 | + utils.PlotlyJSONEncoder.encode_as_datetime, obj) |
| 99 | + |
| 100 | + # should succeed with 'utcoffset', 'isoformat' and '__sub__' attrs |
| 101 | + res = utils.PlotlyJSONEncoder.encode_as_datetime( |
| 102 | + datetime.datetime(2013, 10, 1) |
| 103 | + ) |
| 104 | + self.assertEqual(res, '2013-10-01') |
| 105 | + |
| 106 | + # should not include extraneous microsecond info if DNE |
| 107 | + res = utils.PlotlyJSONEncoder.encode_as_datetime( |
| 108 | + datetime.datetime(2013, 10, 1, microsecond=0) |
| 109 | + ) |
| 110 | + self.assertEqual(res, '2013-10-01') |
| 111 | + |
| 112 | + # should include microsecond info if present |
| 113 | + res = utils.PlotlyJSONEncoder.encode_as_datetime( |
| 114 | + datetime.datetime(2013, 10, 1, microsecond=10) |
| 115 | + ) |
| 116 | + self.assertEqual(res, '2013-10-01 00:00:00.000010') |
| 117 | + |
| 118 | + # should convert tzinfo to utc. Note that in october, we're in EDT! |
| 119 | + # therefore the 4 hour difference is correct. |
| 120 | + naive_datetime = datetime.datetime(2013, 10, 1) |
| 121 | + aware_datetime = pytz.timezone('US/Eastern').localize(naive_datetime) |
| 122 | + |
| 123 | + res = utils.PlotlyJSONEncoder.encode_as_datetime(aware_datetime) |
| 124 | + self.assertEqual(res, '2013-10-01 04:00:00') |
91 | 125 |
|
92 | 126 | ## JSON encoding
|
93 | 127 | numeric_list = [1, 2, 3]
|
|
0 commit comments