Completed
Push — master ( fe49eb...265317 )
by W
06:11
created

st2common.util.parse()   B

Complexity

Conditions 3

Size

Total Lines 24

Duplication

Lines 0
Ratio 0 %
Metric Value
cc 3
dl 0
loc 24
rs 8.9714
1
# Licensed to the StackStorm, Inc ('StackStorm') under one or more
2
# contributor license agreements.  See the NOTICE file distributed with
3
# this work for additional information regarding copyright ownership.
4
# The ASF licenses this file to You under the Apache License, Version 2.0
5
# (the "License"); you may not use this file except in compliance with
6
# the License.  You may obtain a copy of the License at
7
#
8
#     http://www.apache.org/licenses/LICENSE-2.0
9
#
10
# Unless required by applicable law or agreed to in writing, software
11
# distributed under the License is distributed on an "AS IS" BASIS,
12
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
# See the License for the specific language governing permissions and
14
# limitations under the License.
15
16
"""
17
Date related utility functions.
18
"""
19
20
import datetime
21
22
import dateutil.tz
23
import dateutil.parser
24
25
26
__all__ = [
27
    'get_datetime_utc_now',
28
    'add_utc_tz',
29
    'convert_to_utc',
30
    'parse'
31
]
32
33
34
def get_datetime_utc_now():
35
    """
36
    Retrieve datetime object for current time with included UTC timezone info.
37
38
    :rtype: ``datetime.datetime``
39
    """
40
    dt = datetime.datetime.utcnow()
41
    dt = add_utc_tz(dt)
42
    return dt
43
44
45
def add_utc_tz(dt):
46
    if dt.tzinfo and dt.tzinfo.utcoffset(dt) != datetime.timedelta(0):
47
        raise ValueError('datetime already contains a non UTC timezone')
48
49
    return dt.replace(tzinfo=dateutil.tz.tzutc())
50
51
52
def convert_to_utc(dt):
53
    """
54
    Convert provided datetime object to UTC timezone.
55
56
    Note: If the object has no timezone information we assume it's in UTC.
57
58
    :rtype: ``datetime.datetime``
59
    """
60
    if not dt.tzinfo:
61
        return add_utc_tz(dt)
62
63
    dt = dt.astimezone(dateutil.tz.tzutc())
64
    return dt
65
66
67
def parse(value, preserve_original_tz=False):
68
    """
69
    Parse a date string and return a time-zone aware datetime object.
70
71
    :param value: Date in ISO8601 format.
72
    :type value: ``str``
73
74
    :param preserve_original_tz: True to preserve the original timezone - by default result is
75
                                 converted into UTC.
76
    :type preserve_original_tz: ``boolean``
77
78
    :rtype: ``datetime.datetime``
79
    """
80
    # pylint: disable=no-member
81
    # For some reason pylint thinks it returns a tuple but it returns a datetime object
82
    dt = dateutil.parser.parse(str(value))
83
84
    if not dt.tzinfo:
85
        dt = add_utc_tz(dt)
86
87
    if not preserve_original_tz:
88
        dt = convert_to_utc(dt)
89
90
    return dt
91