美文网首页
Django 时区下时间的操作

Django 时区下时间的操作

作者: Sunnky | 来源:发表于2017-12-05 17:35 被阅读0次

    当settings.py中开启时区时:

    TIME_ZONE = 'Asia/Shanghai'
    
    USE_I18N = True
    
    USE_L10N = True
    
    USE_TZ = True
    

    此时进行时间的对比,写入这些,如果用原生的datetime (系统时间),就会报错

    RuntimeWarning: DateTimeField RefundRecord.refund_time received a naive datetime (2017-12-04 16:24:35.860618) while time zone support is active.
    

    因此,需要转换为对应的时区时间

    • 不用utc
    from django.utils import timezone
    now = timezone.now()
    
    • 用utc
    from django.utils.timezone import utc
    utcnow = datetime.datetime.utcnow().replace(tzinfo=utc)
    

    二者的转化:

    def utc2local(utc_st):
        """
        UTC 时间转 系统时间
        :param utc_st: 2017-12-05 18:23:59.585829+08:00
        :return: 2017-12-05 10:22:01
        """
        now_stamp = time.time()
        local_time = datetime.datetime.fromtimestamp(now_stamp)
        utc_time = datetime.datetime.utcfromtimestamp(now_stamp)
        offset = local_time - utc_time
        return utc_st + offset
    
    
    def local2utc(local_st):
        """
        本地时间 转 UTC时间
        :param local_st: 2017-12-05 10:22:01
        :return: 2017-12-05 18:23:59.585829+08:00
        """
        time_struct = time.mktime(local_st.timetuple())
        utc_st = datetime.datetime.utcfromtimestamp(time_struct)
        return utc_st
    

    相关文章

      网友评论

          本文标题:Django 时区下时间的操作

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