python 带时区的日期格式化操作
如下所示:
Wed,23Oct201921:12:01+0800
Wed,23Oct201906:08:37+0000(GMT)
Fri,11Oct201912:42:07+0800(CST)
Wed,23Oct201906:08:37+0000(UTC)
几种不同的日期格式化方式,不同的时区时间转换成北京时间,也就是东八区的时间,注意的是后面的时区表示方式,
defgetTimeStamp(self,date): result=re.search(r"[\-\+]\d+",date) ifresult: time_area=result.group() symbol=time_area[0] offset=int(time_area[1])+int(time_area[2]) ifsymbol=="+": format_str='%a,%d%b%Y%H:%M:%S'+time_area if"UTC"indate: format_str='%a,%d%b%Y%H:%M:%S'+time_area+'(UTC)' if"GMT"indate: format_str='%a,%d%b%Y%H:%M:%S'+time_area+'(GMT)' if"CST"indate: 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) ifoffset>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") returnlocaltimestamp
补充知识:Python处理带timezone的datetime类型
在存储时间类型到数据库的时候,通常使用DateTime类型。使用DateTime类型就会遇到时区timezone的问题。为了能够处理timezone,推荐存数据库的使用存入的是基于UTC的时间日期,在本地取用的时候在转成本地时间。
Python定义了抽象类tzinfo,这个class不能直接使用。3.x版本(至少3.4,3.5)定义了timezoneclass。但是这个timezone还是不如第三方pytz类好用。
还有一个问题就是如何得到本机的timezone。在timeclass里面可以得到一个time.timezone,是一个基于秒的offset值。注意这个time不是datetime.time,就是time,用于os相关的时间信息。不是很好用,推荐tzlocal库。
安装pytz和tzlocal
使用pip安装就可以了。
pipinstallpytz
pipinstalltzlocal
如何使用
得到当前时间,用于数据的存储
fromdatetimeimportdatetime
t=datetime.utcnow()
已知本地时间,需要转成UTC时间用于存储
importpytz fromtzlocalimportget_localzone tz=get_localzone()#获得本地timezone utc=pytz.utc#获得UTCtimezone dt=datetime(2016,6,12,5,0,0) loc_dt=tz.localize(dt)#将DateTime数据贴上timezone utc_dt=loc_dt.astimezone(utc)#转换到新的timezone
已知UTC时间,转本地
importpytz fromtzlocalimportget_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带时区的日期格式化操作就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。