Home >Backend Development >Python Tutorial >Python uses the module pytz to convert time zones
Preface
I recently encountered a problem: my server
and client
are not in the same time zone, The time zone of server
is EDT, which is the Eastern Time Zone of the United States. client
is my own computer. The time zone is China Standard Time Zone, East Eighth District. For testing needs, I need to send a time to server
so that the server can perform some actions at this timestamp. This timestamp is usually the current time plus 2 minutes or a few minutes.
Usually the Eastern United States is 12 hours behind us during daylight saving time, so directly subtract these 12 hours, and then add two minutes, you can send a timestamp based on server
, but only Half of the time is in daylight saving time, so consider doing it based on time zone. After searching on Baidu, Python has a module pytz
that is related to time zones, but it is not a builtin
method, so it needs to be installed.
1. First install pytz, pip install pytz.
2. Test the water and print out the time zone of the United States:
#-*-coding:utf-8-*- #/usr/bin/env python import pytz print(pytz.country_timezones('us'))#[u'America/New_York', u'America/Detroit', u'America/Kentucky/Louisville', u'America/Kentucky/Monticello', u'America/Indiana/Indianapolis', u'America/Indiana/Vincennes', u'America/Indiana/Winamac', u'America/Indiana/Marengo', u'America/Indiana/Petersburg', u'America/Indiana/Vevay', u'America/Chicago', u'America/Indiana/Tell_City', u'America/Indiana/Knox', u'America/Menominee', u'America/North_Dakota/Center', u'America/North_Dakota/New_Salem', u'America/North_Dakota/Beulah', u'America/Denver', u'America/Boise', u'America/Phoenix', u'America/Los_Angeles', u'America/Anchorage', u'America/Juneau', u'America/Sitka', u'America/Metlakatla', u'America/Yakutat', u'America/Nome', u'America/Adak', u'Pacific/Honolulu']
There are so many places, but since it’s the east, just choose New York.
3. Next, print out the current time in East America.
#-*-coding:utf-8-*- #/usr/bin/env python import pytz import time import datetime tz = pytz.timezone('America/New_York') a = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S") print(a)
2016-08-18 02:26:53
4. Convert the time to seconds, add 120 seconds, and then convert back to standard format:
#-*-coding:utf-8-*- #/usr/bin/env python import pytz import time import datetime print(pytz.country_timezones('us')) tz = pytz.timezone('America/New_York') a = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S") print(a) b=time.mktime(time.strptime(a,'%Y-%m-%d %H:%M:%S'))+int(2)*60 print(time.strftime("%Y-%m-%d %H:%M",time.localtime(b)))
#2016-08 -18 02:28
For more articles related to Python using the pytz module to convert time zones, please pay attention to the PHP Chinese website!