Python time zone setting method with pytz query time zone tutorial

  • 2020-04-02 13:16:02
  • OfStack

Time zone concept and conversion

The first thing to know about time zone transitions is simple: subtract the local time from the local time zone, and the rest is Greenwich time. For example, 18:00 in Beijing time is 18:00+08:00, and after subtraction it is 10:00+00:00, so it is 10:00 GMT.
Add Greenwich time to the local time zone and you get local time. For example, 10:00 GMT is 10:00 + 00:00, which translates to PST plus -8 hours, so it's 02:00-08:00.
And Pacific standard time to Beijing time conversion is the same, time zone subtraction can be. For example, the difference between 02:00-08:00 PST and Beijing time is -16 hours, so the result is 18:00 + 08:00.

Python time zone processing
Finding that python has no easy way to handle time zones, I wonder why python doesn't provide a time zone module to handle time zone issues. Fortunately, we have a third-party pytz module that can help us solve the time zone problem.

Pytz simple tutorial

Pytz queries for a time zone
You can find all the time zones for that country by country code.


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

Pytz creates time zone objects
Based on the time zone information obtained above, you can create the specified time zone object. For example, create the Shanghai time zone object:


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

I get the time in a time zone
Then, when the time object is created, the above time zone is specified to get the date time of the specified time zone:


>>> import datetime
>>> datetime.datetime.now(tz)


Related articles: