Skip to content

Commit

Permalink
Add convert_to_utc function, update isotime.parse to convert resultin…
Browse files Browse the repository at this point in the history
…g object to

UTC by default.
  • Loading branch information
Kami committed Jun 13, 2015
1 parent 623ca34 commit 7b4604c
Showing 1 changed file with 26 additions and 5 deletions.
31 changes: 26 additions & 5 deletions st2common/st2common/util/isotime.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
__all__ = [
'get_datetime_utc_now',
'add_utc_tz',
'convert_to_utc',
'format',
'validate',
'parse'
Expand Down Expand Up @@ -52,7 +53,23 @@ def add_utc_tz(dt):
return dt.replace(tzinfo=dateutil.tz.tzutc())


def convert_to_utc(dt):
"""
Convert provided datetime object to UTC timezone.
Note: If the object has no timezone information we assume it's in UTC.
:rtype: ``datetime.datetime``
"""
if not dt.tzinfo:
return add_utc_tz(dt)

dt = dt.astimezone(dateutil.tz.tzutc())
return dt


def format(dt, usec=True, offset=True):
# pylint: disable=no-member
if isinstance(dt, basestring):
dt = parse(dt)
fmt = ISO8601_FORMAT_MICROSECOND if usec else ISO8601_FORMAT
Expand All @@ -74,15 +91,19 @@ def validate(value, raise_exception=True):
return False


def parse(value, convert_to_utc=False):
def parse(value, preserve_original_tz=False):
"""
Parse date in the ISO8601 format and return a time-zone aware datetime object.
:param value: Date in ISO8601 format.
:type value: ``str``
:param convert_to_utc: True to convert resulting timestamp to the UTC timezone.
:type convert_to_utc: ``boolean``
:param preserve_original_tz: True to preserve the original timezone - by default result is
converted into UTC.
:type preserve_original_tz: ``boolean``
:param convert_result_to_utc: True to convert resulting timestamp to the UTC timezone.
:type convert_result_to_utc: ``boolean``
:rtype: ``datetime.datetime``
"""
Expand All @@ -95,7 +116,7 @@ def parse(value, convert_to_utc=False):
if not dt.tzinfo:
dt = add_utc_tz(dt)

if convert_to_utc:
dt = dt.astimezone(dateutil.tz.tzutc())
if not preserve_original_tz:
dt = convert_to_utc(dt)

return dt

0 comments on commit 7b4604c

Please sign in to comment.