OLD | NEW |
1 # Copyright 2015 The Chromium Authors. All rights reserved. | 1 # Copyright 2015 The Chromium Authors. All rights reserved. |
2 # Use of this source code is governed by a BSD-style license that can be | 2 # Use of this source code is governed by a BSD-style license that can be |
3 # found in the LICENSE file. | 3 # that can be found in the LICENSE file. |
4 | 4 |
5 | 5 |
6 """Provides common timestamp functions.""" | 6 """Provides common timestamp functions.""" |
7 | 7 |
8 import datetime | 8 import datetime |
9 import pytz | 9 import pytz |
10 | 10 |
11 | 11 |
12 def utctimestamp(dt): | 12 def utctimestamp(dt): |
13 """Converts a datetime object into a floating point timestamp since the epoch. | 13 """Converts a datetime object into a floating point timestamp since the epoch. |
14 | 14 |
15 dt is the datetime to convert. If dt is a naive (non-tz-aware) object, it | 15 dt is the datetime to convert. If dt is a naive (non-tz-aware) object, it |
16 will implicitly be treated as UTC. | 16 will implicitly be treated as UTC. |
17 """ | 17 """ |
18 epoch = datetime.datetime.utcfromtimestamp(0).replace(tzinfo=pytz.UTC) | 18 epoch = datetime.datetime.utcfromtimestamp(0).replace(tzinfo=pytz.UTC) |
19 # This check is from http://stackoverflow.com/a/27596917/3984761. | 19 # This check is from http://stackoverflow.com/a/27596917/3984761. |
20 if dt.tzinfo is None or dt.tzinfo.utcoffset(dt) is None: | 20 if dt.tzinfo is None or dt.tzinfo.utcoffset(dt) is None: |
21 dt = dt.replace(tzinfo=pytz.UTC) | 21 dt = dt.replace(tzinfo=pytz.UTC) |
22 return (dt - epoch).total_seconds() | 22 return (dt - epoch).total_seconds() |
23 | 23 |
24 | 24 |
25 def utcnow_ts(): # pragma: no cover | 25 def utcnow_ts(): # pragma: no cover |
26 """Returns the floating point number of seconds since the UTC epoch.""" | 26 """Returns the floating point number of seconds since the UTC epoch.""" |
27 return utctimestamp(datetime.datetime.utcnow()) | 27 return utctimestamp(datetime.datetime.utcnow()) |
OLD | NEW |