python项目中很多时候会需要将时间在datetime格式和timestamp格式之间转化,又或者你需要将utc时间转化为本地时间,本文总结了这几个时间之间转化的函数,供大家参考。
一、Datetime转化为TimeStamp
def datetime2timestamp(dt, convert_to_utc=False): ''' Converts a datetime object to UNIX timestamp in milliseconds. ''' if isinstance(dt, datetime.datetime): if convert_to_utc: # 是否转化为UTC时间 dt = dt + datetime.timedelta(hours=-8) # 中国默认时区 timestamp = total_seconds(dt - EPOCH) return long(timestamp) return dt
登录后复制
二、TimeStamp转化为Datetime
def timestamp2datetime(timestamp, convert_to_local=False): ''' Converts UNIX timestamp to a datetime object. ''' if isinstance(timestamp, (int, long, float)): dt = datetime.datetime.utcfromtimestamp(timestamp) if convert_to_local: # 是否转化为本地时间 dt = dt + datetime.timedelta(hours=8) # 中国默认时区 return dt return timestamp
登录后复制
三、当前UTC时间的TimeStamp
def timestamp_utc_now(): return datetime2timestamp(datetime.datetime.utcnow())
登录后复制
四、当前本地时间的TimeStamp
def timestamp_now(): return datetime2timestamp(datetime.datetime.now())
登录后复制
五、UTC时间转化为本地时间
# 需要安装python-dateutil# Ubuntu下:sudo apt-get install python-dateutil# 或者使用PIP:sudo pip install python-dateutilfrom dateutil import tzfrom dateutil.tz import tzlocalfrom datetime import datetime # get local time zone nameprint datetime.now(tzlocal()).tzname() # UTC Zonefrom_zone = tz.gettz('UTC')# China Zoneto_zone = tz.gettz('CST') utc = datetime.utcnow() # Tell the datetime object that it's in UTC time zoneutc = utc.replace(tzinfo=from_zone) # Convert time zonelocal = utc.astimezone(to_zone)print datetime.strftime(local, "%Y-%m-%d %H:%M:%S")
登录后复制
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。
发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2306445.html