获取当前东八区时间以及统一时区的时间比较
# coding: utf-8 import pytz import datetime # 定义东八区时区 cst_timezone = pytz.timezone('Asia/Shanghai') # 获取东八区的当前时间 def get_cst_nowtime(): return datetime.datetime.now(cst_timezone) # 将时间对象转换为东八区时间 def to_cst_zone(req_time): if req_time.tzinfo is None: # 如果没有时区信息,假定为本地无时区时间并设置为东八区 return req_time.replace(tzinfo=cst_timezone) elif req_time.tzinfo != cst_timezone: # 如果时区信息不等于东八区,则转换为东八区 return req_time.astimezone(cst_timezone) else: return req_time # 将两个时间统一为东八区并进行比较 def compare_times_to_cst(timt1, time2): # 转换两个时间为东八区 time1 = to_cst_zone(timt1) time2 = to_cst_zone(time2) # 比较两个时间 if time1 > time2: return 1 elif time1 < time2: return -1 else: return 0 if __name__ == '__main__': from datetime import datetime # CST server_time = datetime.now(pytz.timezone('Asia/Shanghai')) print("server_time:", server_time) # UTC db_time_utc = datetime.now(pytz.timezone('UTC')) print("db_time_utc:", db_time_utc) print(compare_times_to_cst(db_time_utc, server_time))
~~~
123
123
标签:东八区,Python,return,datetime,timezone,处理,time,cst,时区 From: https://www.cnblogs.com/paulwhw/p/18569812