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)
  • 相关阅读:
    2015 8月 做题记录
    Nim及SG函数
    CodeForces
    CF 546E(最大流
    CF 544E(状压
    树形DP
    HDU 4173(计算几何
    HDU 4081(最小生成树
    codeforeces 540E(树状数组
    Linux nginx安装
  • 原文地址:https://www.cnblogs.com/xiaomage666/p/11386979.html
Copyright © 2011-2022 走看看