Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(303)

Unified Diff: infra/libs/time_functions/timestamp.py

Issue 1094253002: Adds two convenience functions for later use. (Closed) Base URL: https://chromium.googlesource.com/infra/infra.git@master
Patch Set: Created 5 years, 8 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View side-by-side diff with in-line comments
Download patch
Index: infra/libs/time_functions/timestamp.py
diff --git a/infra/libs/time_functions/timestamp.py b/infra/libs/time_functions/timestamp.py
new file mode 100644
index 0000000000000000000000000000000000000000..2bda0a10638cb787c32abbad85e96942873055f3
--- /dev/null
+++ b/infra/libs/time_functions/timestamp.py
@@ -0,0 +1,27 @@
+# Copyright 2015 The Chromium Authors. All rights reserved.
+# Use of this source code is governed by a BSD-style license that can be
+# found in the LICENSE file.
+
+
+"""Provides common timestamp functions."""
+
+import datetime
+import pytz
+
+
+def utctimestamp(dt):
tandrii(chromium) 2015/04/24 18:10:43 why no underscore? IMO, it's harder to read than u
+ """Converts a datetime object into a floating point timestamp since the epoch.
+
+ dt is the datetime to convert. If dt is a naive (non-tz-aware) object, it
+ will implicitly be treated as UTC.
+ """
+ epoch = datetime.datetime.utcfromtimestamp(0).replace(tzinfo=pytz.UTC)
+ # This check is from http://stackoverflow.com/a/27596917/3984761.
+ if dt.tzinfo is None or dt.tzinfo.utcoffset(dt) is None:
+ dt = dt.replace(tzinfo=pytz.UTC)
+ return (dt - epoch).total_seconds()
+
+
+def utcnow_ts(): # pragma: no cover
+ """Returns the floating point number of seconds since the UTC epoch."""
+ return utctimestamp(datetime.datetime.utcnow())

Powered by Google App Engine
This is Rietveld 408576698