Python用模块pytz来转换时区

yipeiwu_com6年前Python基础

前言

最近遇到了一个问题:我的serverclient不是在一个时区,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能有所帮助。

相关文章

如何利用Boost.Python实现Python C/C++混合编程详解

前言 学习中如果碰到问题,参考官网例子: D:\boost_1_61_0\libs\python\test 参考:Boost.Python 中英文文档。 利用Boost.Python...

Django使用unittest模块进行单元测试过程解析

Django测试框架非常简单,首选方法是使用python标准库中的unittest模块。 Writing tests Django的单元测试使用python的unittest模块,这个...

TensorFlow索引与切片的实现方法

TensorFlow索引与切片的实现方法

索引与切片在Tensorflow中使用的频率极其高,可以用来提取部分数据。 1.索引 在 TensorFlow 中,支持基本的[𝑖][𝑗]…标准索引方...

Python3.4 splinter(模拟填写表单)使用方法

如下所示: from splinter.browser import Browser b = Browser('chrome') url = 'https://kyfw.12...

python代理工具mitmproxy使用指南

python代理工具mitmproxy使用指南

前言 mitmproxy 是 man-in-the-middle proxy 的简称,译为中间人代理工具,可以用来拦截、修改、保存 HTTP/HTTPS 请求。以命令行终端形式呈现,操作...