Python用模块pytz来转换时区

yipeiwu_com7年前Python基础

前言

最近遇到了一个问题:我的server和client不是在一个时区,server时区是EDT,即美国东部时区,client,就是我自己的电脑,时区是中国标准时区,东八区。处于测试需要,我需要向server发送一个时间,使得server在这个时间戳去执行一些动作。这个时间戳通常是当前时间加2分钟或者几分钟。

通常美东在夏令时时,和我们相差12小时,所以直接减掉这12小时,然后再加两分钟,可以实现发送基于server的时间戳,但是只有一半时间是夏令时,所以考虑还是基于时区来做。百度了一下,Python有一个模块pytz是时区相关的,但不是builtin方法,所以需要安装一下。

1. 首先安装pytz,pip install pytz.

2. 试了一下水,打印出美国的时区:

#-*-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']

这个地方还真多,不过既然是东部,直接选New York就好了。

3. 下一步,打印出美东的current time。

#-*-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. 将时间转换为秒,加上120秒,然后再转换回标准格式:

#-*-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

总结

以上就是在Python用模块pytz来转换时区的全部内容,希望本文的内容对大家学习使用Python能有所帮助。

相关文章

tensorflow识别自己手写数字

tensorflow识别自己手写数字

tensorflow作为google开源的项目,现在赶超了caffe,好像成为最受欢迎的深度学习框架。确实在编写的时候更能感受到代码的真实存在,这点和caffe不同,caffe通过编写配...

对python3新增的byte类型详解

对python3新增的byte类型详解

在python2中字节类型同字符类型区分不大,但是在python3中最重要的特性是对文本和二进制数据做了更加清晰的区分,文本总是Unicode,由字符类型表示,而二进制数据则由byte类...

python 发送和接收ActiveMQ消息的实例

ActiveMQ是java开发的消息中间件服务。可以支持多种协议(AMQP,MQTT,OpenWire,Stomp),默认的是OpenWire。而python与ActiveMQ的通信使用...

Python素数检测实例分析

本文实例讲述了Python素数检测的方法。分享给大家供大家参考。具体如下: 该程序实现了素数检测器功能,如果结果是true,则是素数,如果结果是false,则不是素数。 def fn...

win10子系统python开发环境准备及kenlm和nltk的使用教程

前言 因为NLP作业需要用到kenlm,而kenlm在linux下更为方便。本人win10之前开启了子系统,所以就打算在子系统下进行相关作业的完成。 首先开启win10子系统,网上教...