1#
2# Copyright (C) 2018 The Android Open Source Project
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# 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
17import logging
18import pytz
19
20
21def GetTimeWithTimezone(dt, timezone="US/Pacific"):
22    """Converts timezone of datetime.datetime() instance.
23
24    Args:
25        dt: datetime.datetime() instance.
26        timezone: a string representing timezone listed in TZ database.
27
28    Returns:
29        datetime.datetime() instance with the given timezone.
30    """
31    if not dt:
32        return None
33    utc_time = dt.replace(tzinfo=pytz.utc)
34    try:
35        converted_time = utc_time.astimezone(pytz.timezone(timezone))
36    except pytz.UnknownTimeZoneError as e:
37        logging.exception(e)
38        converted_time = dt
39    return converted_time
40