Skip to content

Commit da1d823

Browse files
committed
issue_21 - timezone offset for datetime strings fixed, debug fixes, whitespace cleanup
1 parent b715364 commit da1d823

File tree

1 file changed

+37
-17
lines changed

1 file changed

+37
-17
lines changed

datemath/helpers.py

Lines changed: 37 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -42,9 +42,11 @@
4242
import re
4343
import os
4444
from dateutil import tz
45+
import dateutil
4546
import sys
47+
from pprint import pprint
4648

47-
debug = True if os.environ.get('DEBUG') == 'true' else False
49+
debug = True if os.environ.get('DATEMATH_DEBUG') else False
4850

4951
class DateMathException(Exception):
5052
pass
@@ -75,7 +77,7 @@ def unitMap(c):
7577

7678
def as_datetime(expression, now, tz='UTC'):
7779
'''
78-
returs our datemath expression as a python datetime object
80+
returns our datemath expression as a python datetime object
7981
note: this has been deprecated and the 'type' argument in parse is the current way
8082
'''
8183
return parse(expression, now, tz)
@@ -89,26 +91,28 @@ def parse(expression, now=None, tz='UTC', type=None, roundDown=True):
8991
:param type - if we are dealing with a arrow or datetime object
9092
:param roundDown - wether or not we should round up or round down on this. default is roundDown=True, which means if it was 12:00:00, `/d` would be '00:00:00', and with roundDown=False, `/d` would be '29:59:59'
9193
'''
94+
if debug: print("parse() - starting for expression: {}".format(expression))
9295
if now is None:
96+
if debug: print("parse() - Now is None, setting now to utcnow()")
9397
now = arrow.utcnow()
9498

95-
if debug: print("Orig Expression: {0}".format(expression))
99+
if debug: print("parse() - Orig Expression: {0}".format(expression))
96100

97101
math = ''
98102
time = ''
99103

100104
if 'UTC' not in tz:
101-
if debug: print("will now convert tz to {0}".format(tz))
105+
if debug: print("parse() - will now convert tz to {0}".format(tz))
102106
now = now.to(tz)
103107

104108
if expression == 'now':
105-
if debug: print("Now, no dm: {0}".format(now))
109+
if debug: print("parse() - Now, no dm: {0}".format(now))
106110
if type:
107111
return getattr(now, type)
108112
else:
109113
return now
110114
elif re.match('\d{10,}', str(expression)):
111-
if debug: print('found an epoch timestamp')
115+
if debug: print('parse() - found an epoch timestamp')
112116
if len(str(expression)) == 13:
113117
raise DateMathException('Unable to parse epoch timestamps in millis, please convert to the nearest second to continue - i.e. 1451610061 / 1000')
114118
ts = arrow.get(int(expression))
@@ -118,7 +122,7 @@ def parse(expression, now=None, tz='UTC', type=None, roundDown=True):
118122
''' parse our standard "now+1d" kind of queries '''
119123
math = expression[3:]
120124
time = now
121-
if debug: print('now expression: {0}'.format(now))
125+
if debug: print('parse() - now expression: {0}'.format(now))
122126
else:
123127
''' parse out datemath with date, ex "2015-10-20||+1d" '''
124128
if '||' in expression:
@@ -137,24 +141,40 @@ def parse(expression, now=None, tz='UTC', type=None, roundDown=True):
137141

138142
if not math or math == '':
139143
rettime = time
144+
140145
rettime = evaluate(math, time, tz, roundDown)
141146

142147
if type:
143148
return getattr(rettime, type)
144149
else:
145150
return rettime
146151

147-
148152
def parseTime(timestamp, timezone='UTC'):
149153
'''
150-
parses a date/time stamp and returns and arrow object
154+
parses a datetime string and returns and arrow object
151155
'''
152156
if timestamp and len(timestamp) >= 4:
153157
ts = arrow.get(timestamp)
154-
ts = ts.replace(tzinfo=timezone)
155-
return ts
158+
if debug: print("parseTime() - ts = {} :: vars :: {}".format(ts, vars(ts)))
159+
if debug: print("parseTime() - ts timezone = {}".format(ts.tzinfo))
160+
if debug: print("parseTime() - tzinfo type = {}".format(type(ts.tzinfo)))
161+
if debug: print("parseTime() - timezone that came in = {}".format(timezone))
162+
163+
if ts.tzinfo:
164+
import dateutil
165+
if isinstance(ts.tzinfo, dateutil.tz.tz.tzoffset):
166+
# this means our TZ probably came in via our datetime string
167+
# then lets set our tz to whatever tzoffset is
168+
ts = ts.replace(tzinfo=ts.tzinfo)
169+
elif isinstance(ts.tzinfo, dateutil.tz.tz.tzutc):
170+
# otherwise if we are utc, then lets just set it to be as such
171+
ts = ts.replace(tzinfo=timezone)
172+
else:
173+
# otherwise lets just ensure its set to whatever timezone came in
174+
ts = ts.replace(tzinfo=timezone)
156175

157-
176+
return ts
177+
158178
def roundDate(now, unit, tz='UTC', roundDown=True):
159179
'''
160180
rounds our date object
@@ -163,7 +183,7 @@ def roundDate(now, unit, tz='UTC', roundDown=True):
163183
now = now.floor(unit)
164184
else:
165185
now = now.ceil(unit)
166-
if debug: print("roundDate Now: {0}".format(now))
186+
if debug: print("roundDate() Now: {0}".format(now))
167187
return now
168188

169189
def calculate(now, offsetval, unit):
@@ -175,7 +195,7 @@ def calculate(now, offsetval, unit):
175195
offsetval = int(offsetval)
176196
try:
177197
now = now.shift(**{unit: offsetval})
178-
if debug: print("Calculate called: now: {}, offsetval: {}, offsetval-type: {}, unit: {}".format(now, offsetval, type(offsetval), unit))
198+
if debug: print("calculate() called: now: {}, offsetval: {}, offsetval-type: {}, unit: {}".format(now, offsetval, type(offsetval), unit))
179199
return now
180200
except Exception as e:
181201
raise DateMathException('Unable to calculate date: now: {0}, offsetvalue: {1}, unit: {2} - reason: {3}'.format(now,offsetval,unit,e))
@@ -184,8 +204,8 @@ def evaluate(expression, now, timeZone='UTC', roundDown=True):
184204
'''
185205
evaluates our datemath style expression
186206
'''
187-
if debug: print('Expression: {0}'.format(expression))
188-
if debug: print('Now: {0}'.format(now))
207+
if debug: print('evaluate() - Expression: {0}'.format(expression))
208+
if debug: print('evaluate() - Now: {0}'.format(now))
189209
val = 0
190210
i = 0
191211
while i < len(expression):
@@ -221,7 +241,7 @@ def evaluate(expression, now, timeZone='UTC', roundDown=True):
221241
raise DateMathException(''''{}' is not a valid timeunit for expression: '{}' '''.format(char, expression))
222242

223243
i += 1
224-
if debug: print("Fin: {0}".format(now))
244+
if debug: print("evaluate() - Finished: {0}".format(now))
225245
if debug: print('\n\n')
226246
return now
227247

0 commit comments

Comments
 (0)