|
12 | 12 | import threading
|
13 | 13 | import re
|
14 | 14 | import datetime
|
| 15 | +import pytz |
15 | 16 |
|
16 | 17 | try:
|
17 | 18 | import numpy
|
@@ -93,11 +94,18 @@ def ensure_dir_exists(directory):
|
93 | 94 |
|
94 | 95 | def iso_to_plotly_time_string(iso_string):
|
95 | 96 | """Remove timezone info and replace 'T' delimeter with ' ' (ws)."""
|
96 |
| - no_tz_string = '-'.join(iso_string.split('-')[:3]) |
97 |
| - if no_tz_string.endswith('T00:00:00'): |
98 |
| - return no_tz_string.replace('T00:00:00', '') |
| 97 | + # make sure we don't send timezone info to plotly |
| 98 | + if (iso_string.split('-')[:3] is '00:00') or\ |
| 99 | + (iso_string.split('+')[0] is '00:00'): |
| 100 | + raise Exception("Plotly won't accept timestrings with timezone info.\n" |
| 101 | + "All timestrings are assumed to be in UTC.") |
| 102 | + |
| 103 | + iso_string = iso_string.replace('-00:00', '').replace('+00:00', '') |
| 104 | + |
| 105 | + if iso_string.endswith('T00:00:00'): |
| 106 | + return iso_string.replace('T00:00:00', '') |
99 | 107 | else:
|
100 |
| - return no_tz_string.replace('T', ' ') |
| 108 | + return iso_string.replace('T', ' ') |
101 | 109 |
|
102 | 110 |
|
103 | 111 | ### Custom JSON encoders ###
|
@@ -215,9 +223,22 @@ def encode_as_numpy(obj):
|
215 | 223 | @staticmethod
|
216 | 224 | def encode_as_datetime(obj):
|
217 | 225 | """Attempt to convert to utc-iso time string using datetime methods."""
|
| 226 | + |
| 227 | + # first we need to get this into utc |
| 228 | + try: |
| 229 | + obj = obj.astimezone(pytz.utc) |
| 230 | + except ValueError: |
| 231 | + # we'll get a value error if trying to convert with naive datetime |
| 232 | + pass |
| 233 | + except TypeError: |
| 234 | + # pandas throws a typeerror here instead of a value error, it's OK |
| 235 | + pass |
| 236 | + except AttributeError: |
| 237 | + # we'll get an attribute error if astimezone DNE |
| 238 | + raise NotEncodable |
| 239 | + |
| 240 | + # now we need to get a nicely formatted time string |
218 | 241 | try:
|
219 |
| - if obj.utcoffset(): |
220 |
| - obj = obj - obj.utcoffset() |
221 | 242 | time_string = obj.isoformat()
|
222 | 243 | except AttributeError:
|
223 | 244 | raise NotEncodable
|
|
0 commit comments