温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

python 实现带时区日期格式化

发布时间:2020-10-26 14:34:40 来源:亿速云 阅读:480 作者:Leah 栏目:开发技术

今天就跟大家聊聊有关python 实现带时区日期格式化,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

如下所示:

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_area
        if "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 -8
        tempsTime = tempsTime + datetime.timedelta(hours=offset)
        localtimestamp = tempsTime.strftime("%Y-%m-%d")
      else:
        format_str = '%a, %d %b %Y %H:%M:%S ' + time_area
        utcdatetime = 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 pytz
from tzlocal import get_localzone
tz = get_localzone()  #获得本地timezone
utc = pytz.utc     #获得UTC timezone
dt = datetime(2016, 6, 12, 5, 0, 0)
loc_dt = tz.localize(dt) #将DateTime数据贴上timezone
utc_dt = loc_dt.astimezone(utc)  #转换到新的timezone

已知UTC时间,转本地

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

看完上述内容,你们对python 实现带时区日期格式化有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注亿速云行业资讯频道,感谢大家的支持。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI