Chromium Code Reviews| OLD | NEW |
|---|---|
| 1 # Copyright 2016 The Chromium Authors. All rights reserved. | 1 # Copyright 2016 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 # found in the LICENSE file. |
| 4 | 4 |
| 5 import calendar | 5 import calendar |
| 6 from datetime import datetime | 6 from datetime import datetime |
| 7 from datetime import time | 7 from datetime import time |
| 8 from datetime import timedelta | 8 from datetime import timedelta |
| 9 | 9 |
| 10 import pytz | 10 import pytz |
| (...skipping 48 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... | |
| 59 | 59 |
| 60 Args: | 60 Args: |
| 61 timezone_name (str): The name of any timezone supported by pytz. | 61 timezone_name (str): The name of any timezone supported by pytz. |
| 62 date_time (datetime.datetime): The optional datetime to be converted into | 62 date_time (datetime.datetime): The optional datetime to be converted into |
| 63 the new timezone. | 63 the new timezone. |
| 64 | 64 |
| 65 Returns: | 65 Returns: |
| 66 A datetime.datetime of the given one in the specified timezone. | 66 A datetime.datetime of the given one in the specified timezone. |
| 67 """ | 67 """ |
| 68 return date_time.astimezone(pytz.timezone(timezone_name)) | 68 return date_time.astimezone(pytz.timezone(timezone_name)) |
| 69 | |
| 70 | |
| 71 class TimeZoneInfo(object): | |
|
stgao
2016/11/02 02:04:20
We already have the code to handle this in https:/
Sharu Jiang
2016/11/03 20:59:48
Sure, I can refactor that code to use this TimeZon
| |
| 72 """Gets time zone info from string like: +0800. | |
| 73 | |
| 74 The string is HHMM offset relative to UTC timezone.""" | |
| 75 | |
| 76 def __init__(self, offset_str): | |
| 77 super(TimeZoneInfo, self).__init__() | |
| 78 self._utcoffset = self.GetOffsetFromStr(offset_str) | |
| 79 | |
| 80 def GetOffsetFromStr(self, offset_str): | |
| 81 offset = int(offset_str[-4:-2]) * 60 + int(offset_str[-2:]) | |
| 82 if offset_str[0] == '-': | |
| 83 offset = -offset | |
| 84 return timedelta(minutes=offset) | |
| 85 | |
| 86 @property | |
| 87 def utcoffset(self): | |
| 88 return self._utcoffset | |
| 89 | |
| 90 def LocalToUTC(self, naive_time): | |
| 91 """Localizes naive datetime and converts it to utc naive datetime. | |
| 92 | |
| 93 Args: | |
| 94 naive_time(datetime): naive time in local time zone, for example '+0800'. | |
| 95 | |
| 96 Return: | |
| 97 A naive datetime object in utc time zone. | |
| 98 For example: | |
| 99 For TimeZoneInfo('+0800'), and naive local time is | |
| 100 datetime(2016, 9, 1, 10, 0, 0), the returned result should be | |
| 101 datetime(2016, 9, 1, 18, 0, 0) in utc time. | |
| 102 """ | |
| 103 return naive_time - self.utcoffset | |
| OLD | NEW |