5.2 API Development Key Points and Case Studies

Key Points

  • Timezone Conversion

Preparation Before Class

Install pytz in advance.

pip install pytz

pip install --upgrade tencentcloud-sdk-python

Course Content

Timezone Conversion

For details, see the official documentation.

# Jodoo uses UTC as the standard timezone for Date&Time values. As China is in UTC+8 timezone, the string 
# "2020-04-14T07:32:22.000Z" in Jodoo will be eight hours behind the local time, which is '2020-04-14 15:32:22'

# You can use pytz to convert between timezones.

import datetime
import pytz

# Steps for timezone conversion
# UTC str -> UTC datetime -> Convert timezone -> Local datetime -> Local str

def utc_to_local(utc_time_str, utc_format='%Y-%m-%dT%H:%M:%S.000Z'):
    local_timezone = pytz.timezone('Asia/Shanghai')
    local_format = "%Y-%m-%d %H:%M:%S"
    utc_datetime = datetime.datetime.strptime(utc_time_str, utc_format)
    local_datetime = utc_datetime.replace(tzinfo=pytz.utc).astimezone(local_timezone)
    local_time_str = local_datetime.strftime(local_format)
    return local_time_str

def local_to_utc(local_time_str, local_format = "%Y-%m-%d %H:%M:%S"):
    local_timezone = pytz.timezone('Asia/Shanghai')
    utc_format="%Y-%m-%dT%H:%M:%S.000Z"
    local_datetime = datetime.datetime.strptime(local_time_str, local_format)
    local_datetime = local_timezone.localize(local_datetime, is_dst=None)
    utc_datetime = local_datetime.astimezone(pytz.utc)
    utc_time_str = utc_datetime.strftime(utc_format)
    return utc_time_str

Was this information helpful?
Yes
NoNo
Need more help? Contact support