美文网首页Python
Python常用UTC时间转换

Python常用UTC时间转换

作者: 霡霂976447044 | 来源:发表于2020-07-01 17:37 被阅读0次

    对传入的时间戳转化为UCT的datetime

    start_time = datetime.datetime.utcfromtimestamp(start_timestamp)
    

    将UTC的datetime转化为本地datetime

    def utc2local(utc):
        """将UTC的datetime转换为本地时间"""
        epoch = time.mktime(utc.timetuple())
        offset = datetime.fromtimestamp(epoch) - datetime.utcfromtimestamp(epoch)
        return utc + offset
    

    将字符串格式的时间转化为UTC时间

    def date_str_to_datetime(date_str):
        """将字符串转化为utc时间"""
        try:
            tmp_date = datetime.datetime.strptime(date_str, current_config.DATE_FORMAT)
            tmp_date = datetime.datetime.utcfromtimestamp(tmp_date.timestamp())
        except Exception:
            return None
        else:
            return tmp_date
    

    相关文章

      网友评论

        本文标题:Python常用UTC时间转换

        本文链接:https://www.haomeiwen.com/subject/xgshqktx.html