Advertisement

使用Python实现GMT和UTC和UNIX时间戳相互转换

阅读量:

GMT:即格林尼治标准时间

UTC 即全称是协调世界时。采用GMT作为参考的时间区划分中,英国格林尼治天文台旧址所在的区域定义为零时区。中国的首都北京位于东八区,在此区域内的时间表示为GMT加八小时。

_UNIX时间戳:GMT/UTC时间为起点的统一基准时间为1970-01-01T00:00:00。
获取当前的Unix时间戳:通过调用time模块的时间函数time()来获取当前时刻。
将Unix时间戳转换为普通日期与时间:可以通过调用time.gmtime函数将Unix timestamp转换为普通日期与时间格式。
将普通日期与时间和小时转换回 Unix 时间戳:可通过先解析指定格式的时间字符串为本地时间对象并计算其对应的 Unix 时间戳值。

timedelta(hours=8)只能数组操作

特定的时间点减去八小时后表示为格林尼治标准的时间格式,并赋值给变量date表示该时刻在世界时区中的状态

date = ((datetime.now() - timedelta(hours=8)).strftime("%Y-%m-%dT%H:%M:%S.000Z"))用于将本地当前时间转换为Greenwich Mean Time(GMT)。

Beijingtime代表的时间等于datetime模块中将给定时间戳转换为本地时间的方法计算的结果;Londontime代表的时间等于datetime模块中将给定时间戳转换为格林尼治时间的方法计算的结果

复制代码
 """

    
 时间转换操作
    
 """
    
 from datetime import datetime, timedelta
    
 import time
    
  
    
  
    
 def get_timestamp():
    
     """
    
     将本地时间转换为iso861timestamp
    
     :return:
    
     """
    
     now = datetime.now()
    
     t = now.isoformat("T", "milliseconds")
    
     return t + "Z"
    
  
    
  
    
 def TimestampIso8601_to_BeijingTime(timestamp_iso8601):
    
     """
    
     将iso861timestamp转换为北京时间
    
     :return:
    
     """
    
     if "." not in timestamp_iso8601:    # 当毫秒为0
    
     utc = datetime.strptime(timestamp_iso8601, '%Y-%m-%dT%H:%M:%SZ')
    
     else:
    
     utc = datetime.strptime(timestamp_iso8601, '%Y-%m-%dT%H:%M:%S.%fZ')
    
     now_time = (utc + timedelta(hours=8)).replace(microsecond=0)
    
     return now_time
    
  
    
  
    
 def datetime_to_ISO8601(datetime_type):
    
     """
    
     :param datetime_type:
    
     :return:        将datetime类型时间转换为iso8601格式时间
    
     """
    
     iso8601_type = (datetime_type - timedelta(hours=8)).isoformat("T", "milliseconds") + "Z"
    
     return iso8601_type
    
  
    
  
    
 def string_to_datetime(string):
    
     """
    
     :param string:
    
     :return:       将字符串转换为datatime类型时间  秒级
    
     """
    
     datetime_type = datetime.strptime(string, '%Y-%m-%d %H:%M:%S')
    
     return datetime_type
    
  
    
  
    
 def datetime_to_string(_datetime):
    
     str_time = _datetime.strftime('%Y-%m-%d %H:%M:%S')
    
     return str_time
    
  
    
  
    
 def timestamp_to_datetime(timestamp):
    
     '''
    
     timestamp   ----->  BeijingTime
    
     :param timestamp:
    
     :return:
    
     '''
    
     utc = datetime.fromtimestamp(timestamp / 1000).replace(second=0, microsecond=0)      # 将时间戳转换为北京时间
    
     BeijingTime = utc + timedelta(hours=8)
    
     return BeijingTime
    
  
    
  
    
 def string_to_timestamp(string):
    
     """
    
     string  ----->  timestamp
    
     :param string:
    
     :return:
    
     """
    
     timestamp = int(time.mktime(time.strptime(string, "%Y-%m-%d %H:%M:%S"))) 
    
     return timestamp
    
    
    
    
    代码解释

全部评论 (0)

还没有任何评论哟~