zoukankan      html  css  js  c++  java
  • python时间类型转换

     

        我们使用python 的datetime模块比较两个时间的前后关系时,会出现报错:

      TypeError: can't compare offset-naive and offset-aware datetimes

      这是因为两个时间不属于同一类型,offset-naive是不含时区的类型,而offset-aware是有时区类型,两者自然不能比较。

      我们可以通过判断datetime对象的tzinfo属性,来获悉他是何种类型

    In [17]: import datetime
     
    In [18]: import pytz
     
    In [19]: now=datetime.datetime.now()
     
    In [20]: now
    Out[20]: datetime.datetime(2016, 11, 13, 16, 23, 37, 488000)
     
    In [21]: now.tzinfo==None
    Out[21]: True

      上述代码中now就是一个offset-naive型,就是一个不含时区的datetime。下面代码可以把它转换为一个含时区的offset-aware型:

    In [22]: now=now.replace(tzinfo=pytz.timezone('UTC'))
     
    In [23]: now
    Out[23]: datetime.datetime(2016, 11, 13, 16, 23, 37, 488000, tzinfo=<UTC>)
     
    In [24]: now.tzinfo
    Out[24]: <UTC>

      同样的,将一个offset-aware型转换为offset-naive型:

    In [25]: now=now.replace(tzinfo=None)
     
    In [26]: now
    Out[26]: datetime.datetime(2016, 11, 13, 16, 23, 37, 488000)
  • 相关阅读:
    Eclipse配置方法注释模板
    彻底清除Github上某个文件以及历史
    eclipse快捷键
    Hibernate执行原生SQL
    API接口规范
    eclipse配置google代码风格
    eclipse format xml
    git撤销commit
    使用postman测试文件上传
    centos7下部署elasticSearch集群
  • 原文地址:https://www.cnblogs.com/xiaomage666/p/11386979.html
Copyright © 2011-2022 走看看