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)