您的位置:首页技术文章
文章详情页

python 带时区的日期格式化操作

浏览:15日期:2022-07-07 11:28:39

如下所示:

Wed, 23 Oct 2019 21:12:01 +0800

Wed, 23 Oct 2019 06:08:37 +0000 (GMT)

Fri, 11 Oct 2019 12:42:07 +0800 (CST)

Wed, 23 Oct 2019 06:08:37 +0000 (UTC)

几种不同的日期格式化方式,不同的时区时间转换成北京时间,也就是东八区的时间,注意的是后面的时区表示方式,

def getTimeStamp(self, date): result = re.search(r'[-+]d+', date) if result: time_area = result.group() symbol = time_area[0] offset = int(time_area[1]) + int(time_area[2]) if symbol == '+':format_str = ’%a, %d %b %Y %H:%M:%S ’+ time_areaif 'UTC' in date: format_str = ’%a, %d %b %Y %H:%M:%S ’+ time_area+ ’ (UTC)’if 'GMT' in date: format_str = ’%a, %d %b %Y %H:%M:%S ’ + time_area + ’ (GMT)’if 'CST' in date: format_str = ’%a, %d %b %Y %H:%M:%S ’ + time_area + ’ (CST)’utcdatetime = time.strptime(date, format_str)tempsTime = time.mktime(utcdatetime)tempsTime = datetime.datetime.fromtimestamp(tempsTime)if offset > 8: offset = offset -8tempsTime = tempsTime + datetime.timedelta(hours=offset)localtimestamp = tempsTime.strftime('%Y-%m-%d') else:format_str = ’%a, %d %b %Y %H:%M:%S ’ + time_areautcdatetime = time.strptime(date, format_str)tempsTime = time.mktime(utcdatetime)tempsTime = datetime.datetime.fromtimestamp(tempsTime)tempsTime = tempsTime + datetime.timedelta(hours=(offset + 8))localtimestamp = tempsTime.strftime('%Y-%m-%d') return localtimestamp

补充知识:Python处理带timezone的datetime类型

在存储时间类型到数据库的时候,通常使用DateTime类型。使用DateTime类型就会遇到时区timezone的问题。为了能够处理timezone, 推荐存数据库的使用存入的是基于UTC的时间日期,在本地取用的时候在转成本地时间。

Python定义了抽象类tzinfo, 这个class不能直接使用。3.x版本(至少3.4, 3.5)定义了timezone class。但是这个timezone还是不如第三方pytz类好用。

还有一个问题就是如何得到本机的timezone。在time class里面可以得到一个time.timezone, 是一个基于秒的offset值。注意这个time不是datetime.time, 就是time,用于os相关的时间信息。不是很好用,推荐tzlocal库。

安装pytz和tzlocal

使用pip安装就可以了。

pip install pytz

pip install tzlocal

如何使用

得到当前时间,用于数据的存储

from datetime import datetime

t = datetime.utcnow()

已知本地时间,需要转成UTC时间用于存储

import pytzfrom tzlocal import get_localzonetz = get_localzone() #获得本地timezoneutc = pytz.utc #获得UTC timezonedt = datetime(2016, 6, 12, 5, 0, 0)loc_dt = tz.localize(dt) #将DateTime数据贴上timezoneutc_dt = loc_dt.astimezone(utc) #转换到新的timezone

已知UTC时间,转本地

import pytzfrom tzlocal import get_localzoneutc = pytz.utctz = get_localzone()t = datetime(x,x,x,x,x,x)utc_dt = utc.localize(t)loc_dt = utc_dt.astimezone(tz)

以上这篇python 带时区的日期格式化操作就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持好吧啦网。

标签: Python 编程
相关文章: