Python time zone setting method and pytz query time zone tutorial

Source: Internet
Author: User
Tags time zones
This article describes how to set the Python time zone and how to query the time zone using pytz. Concept and transformation of time zone

First, you need to know the conversion relationship between the time zones. In fact, this is very simple: subtract the local time from the local time zone, and the rest is the Greenwich Mean Time. For example, Beijing time is +, and + after the subtraction. Therefore, Gmt is adopted.
Add Greenwich mean time to the local time zone to get the local time. For example, if the Greenwich Mean Time is +, the conversion to the Pacific Standard Time is plus-8 hours, so it is.
The Pacific Standard Time is converted to Beijing time, and the time zone is reduced. For example, the standard time of the Pacific Ocean is-, which is different from the Beijing time by-16 hours. Therefore, the result is +.

Processing of Python time zone
It is found that python does not have a simple way to deal with time zones. it does not understand why Python does not provide a time zone module to deal with time zone problems. Fortunately, we have a third-party pytz module that can help us solve the time zone problem.

Pytz simple tutorial

Pytz queries a time zone
You can use the country code to find all time zones in this country.

The code is as follows:


>>> Import pytz
>>> Pytz. country_timezones ('cn ')
['Asia/Shanghai', 'Asia/Harbin', 'Asia/Chongqing ', 'Asia/Urumqi', 'Asia/Kashgar']

Pytz creates a time zone object
You can create a specified time zone object based on the time zone information obtained above. For example, create a Shanghai time zone object:

The code is as follows:


Tz = pytz. timezone ('Asia/Shanghai ')

Get the time of a time zone
Then, specify the above time zone when creating the time object to get the date and time of the specified time zone:

The code is as follows:


>>> Import datetime
>>> Datetime. datetime. now (tz)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.