Advertisement

python北京时间、时间戳、UTC时间

阅读量:

将日期格式转换为时间戳:

将时间戳转换为北京时间:通过调用datetime.datetime.fromtimestamp()方法获取服务文件描述符,并使用 strftime(’%Y-%m-%d %H:%M:%S’) 格式化字符串来输出所需的时间戳

北京时间转成utc时间(TZ格式):
datetime.datetime.strptime(‘2021-04-26 14:22:01’,’%Y-%m-%d %H:%M:%S’).timestamp()
1619418121.0
datetime.datetime.utcfromtimestamp(1619418121.0).strftime(’%Y-%m-%dT%H:%M:%SZ’)
‘2021-04-26T06:22:01Z’

复制代码
    import datetime
    import time
    
    
    def get_utc_timestamp():
    """获取本地时间的TZ格式数据"""
    return datetime.datetime.now().strftime('%Y%m%dT%H%M%SZ')
    
    
    def string_time_to_timestamp(local_time, _format='%Y-%m-%d %H:%M:%S'):
    """将date_time字符串格式时间转换成时间戳;如 2021-07-10 14:20:00 ---->> 1625898014 """
    time_stamp = datetime.datetime.strptime(local_time, _format).timestamp()
    return time_stamp
    
    
    def format_timestamp(timestamp, _format='%Y-%m-%d %H:%M:%S'):
    """将时间戳进行格式化;如1625898014--->2021-07-10 14:20:00"""
    return datetime.datetime.fromtimestamp(timestamp).strftime(_format)
    
    
    def change_alert_alarm_utc_time_to_local(utc_time, local_format="%Y-%m-%d %H:%M:%S"):
    """将utc格式的时间转换成本地时间"""
    utc_time= utc_time.split('.')[0]
    return time.strftime(local_format,
                         time.localtime(time.mktime(time.strptime(utc_time, '%Y-%m-%dT%H:%M:%S')) + 28800))

全部评论 (0)

还没有任何评论哟~