【问题标题】:TypeError: can't subtract offset-naive and offset-aware datetimesTypeError:不能减去偏移天真和偏移感知日期时间
【发布时间】:2017-07-06 21:36:41
【问题描述】:

所以我试图减去 datetime 对象。我从使用 dateutil.parser 得到一个,另一个来自 datetime.now()。我一直收到一个

TypeError: 不能减去 offset-naive 和 offset-aware datetimes

我检查了解决方案,但它们似乎不起作用。代码如下:

import json
from dateutil import parser
from datetime import *

with open(".log") as dataFile: 
   dataFile.seek(0)
   data = []
   line=dataFile.readline()
   data=json.loads(line)
   data=ast.literal_eval(json.dumps(data))
   last=parser.parse(data["TIME"])
   print datetime.now()-last

这是它正在读取的数据行:

{"TIME": "2017-06-29T15:17:27.663Z"}

【问题讨论】:

    标签: python-2.7 python-datetime python-dateutil


    【解决方案1】:

    通过将打印更改为修复它

    print datetime.utcnow().replace(tzinfo=pytz.UTC)-last
    

    【讨论】:

      【解决方案2】:

      我在检查 Key Vault 机密的过期日期时遇到了这个错误。喜欢:

      secret.properties.expires_on - datetime.utcnow() 
      

      我要做的是:

      from datetime import timedelta, datetime, timezone
      
      secret.properties.expires_on - datetime.now(timezone.utc)
      

      datetime.utcnow 不起作用很奇怪,但你知道这只是 IT 世界 ;-)

      【讨论】:

        猜你喜欢
        • 2010-10-22
        • 2021-07-07
        • 2015-06-15
        • 2015-10-17
        • 2020-12-30
        • 2020-11-07
        • 1970-01-01
        • 2021-01-07
        相关资源
        最近更新 更多