Python用模块pytz来转换时区
前言
最近遇到了一个问题:我的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来转换时区相关文章请关注PHP中文网!

热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3汉化版
中文版,非常好用

禅工作室 13.0.1
功能强大的PHP集成开发环境

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

Linux终端中查看Python版本时遇到权限问题的解决方法当你在Linux终端中尝试查看Python的版本时,输入python...

使用FiddlerEverywhere进行中间人读取时如何避免被检测到当你使用FiddlerEverywhere...

如何在10小时内教计算机小白编程基础?如果你只有10个小时来教计算机小白一些编程知识,你会选择教些什么�...

在使用Python的pandas库时,如何在两个结构不同的DataFrame之间进行整列复制是一个常见的问题。假设我们有两个Dat...

Uvicorn是如何持续监听HTTP请求的?Uvicorn是一个基于ASGI的轻量级Web服务器,其核心功能之一便是监听HTTP请求并进�...

攻克Investing.com的反爬虫策略许多人尝试爬取Investing.com(https://cn.investing.com/news/latest-news)的新闻数据时,常常�...
