Skip to content

Commit bc77f3a

Browse files
Merge pull request #18 from nickmaccarthy/issue_16
Support for epoch as input
2 parents b8c0b74 + 4b34045 commit bc77f3a

File tree

3 files changed

+20
-0
lines changed

3 files changed

+20
-0
lines changed

README.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,10 @@ By default datemath return an arrow date object representing your timestamp.
8484
<Arrow [2016-01-01T23:59:00+00:00]>
8585
>>> dm('now/d')
8686
<Arrow [2016-01-01T00:00:00+00:00]>
87+
>>> dm(1451610061) # Timestamp in epoch/unix as int (Please note, we do not support epoch millisecond at this time. Please convert your epoch millis to the nearest second. i.e. 1451610061000/1000)
88+
<Arrow [2016-01-01T01:01:01+00:00]>
89+
>>> dm('1451610061') # Timestamp in epoch/unix as string
90+
<Arrow [2013-05-07T04:24:24+00:00]>
8791
```
8892

8993
If you would rather have a string, you can use arrow's ```.format()``` method.

datemath/helpers.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,13 @@ def parse(expression, now=None, tz='UTC', type=None, roundDown=True):
107107
return getattr(now, type)
108108
else:
109109
return now
110+
elif re.match('\d{10,}', str(expression)):
111+
if debug: print('found an epoch timestamp')
112+
if len(str(expression)) == 13:
113+
raise DateMathException('Unable to parse epoch timestamps in millis, please convert to the nearest second to continue - i.e. 1451610061 / 1000')
114+
ts = arrow.get(int(expression))
115+
ts = ts.replace(tzinfo=tz)
116+
return ts
110117
elif expression.startswith('now'):
111118
''' parse our standard "now+1d" kind of queries '''
112119
math = expression[3:]

tests.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -127,6 +127,15 @@ def testParse(self):
127127
self.assertEqual(dm('now-2.5h').format(iso8601), arrow.utcnow().shift(hours=-2.5).format(iso8601))
128128
self.assertEqual(dm('now-2.5d').format(iso8601), arrow.utcnow().shift(days=-2.5).format(iso8601))
129129

130+
# Test epoch timestamps
131+
self.assertEqual(dm('1451610061').format(iso8601), '2016-01-01T01:01:01+00:00')
132+
self.assertEqual(dm(1367900664).format(iso8601), '2013-05-07T04:24:24+00:00')
133+
134+
self.assertRaises(DateMathException, dm, '1451610061000')
135+
try:
136+
dm(1451610061000)
137+
except DateMathException as e:
138+
self.assertTrue('Unable to parse epoch timestamps in millis' in str(e))
130139

131140
# Catch invalid timeunits
132141
self.assertRaises(DateMathException, dm, '+1,')

0 commit comments

Comments
 (0)