zoukankan      html  css  js  c++  java
  • python本地时间与UTC时间转换

    时间格式转换

    UTC时间格式:2014-09-18T10:42:16.126Z
    普通时间格式:2014-09-18 10:42:16

    >>> import datetime
    
    >>> utc = “2014-09-18T10:42:16.126Z”
    >>> local = “2014-09-18 10:42:16>>> UTC_FORMAT = “%Y-%m-%dT%H:%M:%S.%fZ”
    >>> LOCAL_FORMAT = “%Y-%m-%d %H:%M:%S”
    
    >>> datetime.datetime.strptime(utc, UTC_FORMAT)
    datetime.datetime(2014, 9, 18, 10, 42, 16, 126000)
    
    >>> datetime.datetime.strptime(local, LOCAL_FORMAT)
    datetime.datetime(2014, 9, 18, 10, 42, 16)

    CODE

    函数输入输出类型: datetime.datetime

    import time
    import datetime
    
    
    def utc2local(utc_st):
        “”“UTC时间转本地时间(+8:00)”“”
        now_stamp = time.time()
        local_time = datetime.datetime.fromtimestamp(now_stamp)
        utc_time = datetime.datetime.utcfromtimestamp(now_stamp)
        offset = local_time - utc_time
        local_st = utc_st + offset
        return local_st
    
    def local2utc(local_st):
        “”“本地时间转UTC时间(-8:00)”“”
        time_struct = time.mktime(local_st.timetuple())
        utc_st = datetime.datetime.utcfromtimestamp(time_struct)
        return utc_st
    
    utc_time = datetime.datetime(2014, 9, 18, 10, 42, 16, 126000)
    
    # utc转本地
    local_time = utc2local(utc_time)
    print local_time.strftime(“%Y-%m-%d %H:%M:%S”)
    # output:2014-09-18 18:42:16
    
    
    # 本地转utc
    utc_tran = local2utc(local_time)
    print utc_tran.strftime(“%Y-%m-%d %H:%M:%S”)
    # output:2014-09-18 10:42:16
  • 相关阅读:
    某公司面试的SQL题目
    列存储索引
    JList动态添加元素
    Java中堆、栈、常量池等概念解析
    JButton大小设置问题?
    JAVA中定时器的使用
    线性表和链表的区别
    JTable表头显示问题以及如何让某行选中
    JPanel如何设置背景图片
    关于Scanner调用nextInt()异常try后不能二次输入问题
  • 原文地址:https://www.cnblogs.com/christal-11/p/7651276.html
Copyright © 2011-2022 走看看