Python中实现对Timestamp和Datetime及UTC时间之间的转换
Python项目中很多时候会需要将时间在Datetime格式和TimeStamp格式之间转化,又或者你需要将UTC时间转化为本地时间,本文总结了这几个时间之间转化的函数,供大家参考。
一、Datetime转化为TimeStamp
defdatetime2timestamp(dt,convert_to_utc=False): '''ConvertsadatetimeobjecttoUNIXtimestampinmilliseconds.''' ifisinstance(dt,datetime.datetime): ifconvert_to_utc:#是否转化为UTC时间 dt=dt+datetime.timedelta(hours=-8)#中国默认时区 timestamp=total_seconds(dt-EPOCH) returnlong(timestamp) returndt
二、TimeStamp转化为Datetime
deftimestamp2datetime(timestamp,convert_to_local=False): '''ConvertsUNIXtimestamptoadatetimeobject.''' ifisinstance(timestamp,(int,long,float)): dt=datetime.datetime.utcfromtimestamp(timestamp) ifconvert_to_local:#是否转化为本地时间 dt=dt+datetime.timedelta(hours=8)#中国默认时区 returndt returntimestamp
三、当前UTC时间的TimeStamp
deftimestamp_utc_now(): returndatetime2timestamp(datetime.datetime.utcnow())
四、当前本地时间的TimeStamp
deftimestamp_now(): returndatetime2timestamp(datetime.datetime.now())
五、UTC时间转化为本地时间
#需要安装python-dateutil #Ubuntu下:sudoapt-getinstallpython-dateutil #或者使用PIP:sudopipinstallpython-dateutil fromdateutilimporttz fromdateutil.tzimporttzlocal fromdatetimeimportdatetime #getlocaltimezonename printdatetime.now(tzlocal()).tzname() #UTCZone from_zone=tz.gettz('UTC') #ChinaZone to_zone=tz.gettz('CST') utc=datetime.utcnow() #Tellthedatetimeobjectthatit'sinUTCtimezone utc=utc.replace(tzinfo=from_zone) #Converttimezone local=utc.astimezone(to_zone) printdatetime.strftime(local,"%Y-%m-%d%H:%M:%S")