blob: 0a62209d6d5e64bc7e1902f0653b2fbaf9fce29b [file] [log] [blame]
Jon Wayne Parrott8713a712016-10-04 14:19:01 -07001# Copyright 2015 Google Inc.
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
15"""Helper functions for commonly used utilities."""
16
Jon Wayne Parrott5824ad82016-10-06 09:27:44 -070017
18import calendar
19import datetime
20
Jon Wayne Parrott8713a712016-10-04 14:19:01 -070021import six
22
23
Jon Wayne Parrott5824ad82016-10-06 09:27:44 -070024def utcnow():
25 """Returns the current UTC datetime.
26
27 Returns:
28 datetime: The current time in UTC.
29 """
30 return datetime.datetime.utcnow()
31
32
33def datetime_to_secs(value):
34 """Convert a datetime object to the number of seconds since the UNIX epoch.
35
36 Args:
37 value (datetime): The datetime to convert.
38
39 Returns:
40 int: The number of seconds since the UNIX epoch.
41 """
42 return calendar.timegm(value.utctimetuple())
43
44
Jon Wayne Parrott8713a712016-10-04 14:19:01 -070045def to_bytes(value, encoding='utf-8'):
46 """Converts a string value to bytes, if necessary.
47
48 Unfortunately, ``six.b`` is insufficient for this task since in
49 Python 2 because it does not modify ``unicode`` objects.
50
51 Args:
52 value (Union[str, bytes]): The value to be converted.
53 encoding (str): The encoding to use to convert unicode to bytes.
54 Defaults to "utf-8".
55
56 Returns:
57 bytes: The original value converted to bytes (if unicode) or as
58 passed in if it started out as bytes.
59
60 Raises:
61 ValueError: If the value could not be converted to bytes.
62 """
63 result = (value.encode(encoding)
64 if isinstance(value, six.text_type) else value)
65 if isinstance(result, six.binary_type):
66 return result
67 else:
68 raise ValueError('{0!r} could not be converted to bytes'.format(value))
69
70
71def from_bytes(value):
72 """Converts bytes to a string value, if necessary.
73
74 Args:
75 value (Union[str, bytes]): The value to be converted.
76
77 Returns:
78 str: The original value converted to unicode (if bytes) or as passed in
79 if it started out as unicode.
80
81 Raises:
82 ValueError: If the value could not be converted to unicode.
83 """
84 result = (value.decode('utf-8')
85 if isinstance(value, six.binary_type) else value)
86 if isinstance(result, six.text_type):
87 return result
88 else:
89 raise ValueError(
90 '{0!r} could not be converted to unicode'.format(value))