commit fe03a01c97cb9fd41a07f7f1bb6facb633fdbbd2 Author: Damian Johnson atagar@torproject.org Date: Sun Oct 4 11:46:16 2015 -0700
Adding datetime_to_unix() util function
Our descriptors provide datetime objects. This is great, but often we want a unix timestamp instead. Python's datetime builtin truly sucks so need a util for this. --- docs/change_log.rst | 4 ++++ stem/util/__init__.py | 16 ++++++++++++++++ test/settings.cfg | 1 + test/unit/util/__init__.py | 12 ++++++++++++ 4 files changed, 33 insertions(+)
diff --git a/docs/change_log.rst b/docs/change_log.rst index 727b0cb..cfd26d1 100644 --- a/docs/change_log.rst +++ b/docs/change_log.rst @@ -61,6 +61,10 @@ The following are only available within Stem's `git repository * Unable to read descriptors from data directories on Windows due to their CRLF newlines (:trac:`17051`) * TypeError under python3 when using 'use_mirrors = True' (:trac:`17083`)
+ * **Utilities** + + * Added :func:`stem.util.datetime_to_unix` + * **Interpreter**
* Added a '--tor [path]' argument to specify the tor binary to run. diff --git a/stem/util/__init__.py b/stem/util/__init__.py index 1c18df3..b7f0a3c 100644 --- a/stem/util/__init__.py +++ b/stem/util/__init__.py @@ -18,3 +18,19 @@ __all__ = [ 'test_tools', 'tor_tools', ] + +import datetime + + +def datetime_to_unix(timestamp): + """ + Converts a utc datetime object to a unix timestamp. + + .. versionadded:: 1.5.0 + + :param datetime timestamp: timestamp to be converted + + :returns: **float** for the unix timestamp of the given datetime object + """ + + return (timestamp - datetime.datetime(1970, 1, 1)).total_seconds() diff --git a/test/settings.cfg b/test/settings.cfg index 0b050d5..fffbdcf 100644 --- a/test/settings.cfg +++ b/test/settings.cfg @@ -158,6 +158,7 @@ test.unit_tests |test.unit.util.str_tools.TestStrTools |test.unit.util.system.TestSystem |test.unit.util.tor_tools.TestTorTools +|test.unit.util.__init__.TestBaseUtil |test.unit.descriptor.export.TestExport |test.unit.descriptor.reader.TestDescriptorReader |test.unit.descriptor.remote.TestDescriptorDownloader diff --git a/test/unit/util/__init__.py b/test/unit/util/__init__.py index 04ab051..e755625 100644 --- a/test/unit/util/__init__.py +++ b/test/unit/util/__init__.py @@ -11,3 +11,15 @@ __all__ = [ 'system', 'tor_tools', ] + +import datetime +import time +import unittest + +from stem.util import datetime_to_unix + + +class TestBaseUtil(unittest.TestCase): + def test_datetime_to_unix(self): + self.assertEqual(1344251971.0, datetime_to_unix(datetime.datetime(2012, 8, 6, 11, 19, 31))) + self.assertTrue((time.time() - datetime_to_unix(datetime.datetime.utcnow())) < 2)
tor-commits@lists.torproject.org