使用TZ信息

时间:2018-06-14 21:52:28

标签: python-3.x mongodb datetime pymongo python-datetime

我的应用程序通过Pytz使用TZ感知日期时间(用于时间戳和其他信息)。当我写数据(包括datetime obj)时,我将其写为dict viz collection.insert_one

我发现Mongo以下列格式存储数据:

  

2018-05-01 05:05:13.870751 + 05:30

当我使用查询从服务器检索数据时,我将数据作为字符串获取。

我使用以下包装函数来获取数据(并将查询抽象为我的其余代码):

def getdetailsbykey(self, collection_name, keydict):
        if 'dict' not in str(type(keydict)):
            return None
        collection = self.database[collection_name]
        data = collection.find_one(keydict, {'_id' : 0})
        return data

数据本身采用以下格式:

x = db.database.get_collection('incidents', codec_options=CodecOptions(tz_aware=True)).find_one()

x = db.getdetailsbykey('incidents', {'incidentid': '1593d050fe02a25164f12645faa88c6c'})

(例如)

返回:

{'_id': ObjectId('5ae39283f8b6491f8f16296d'),
 'distance': 0,
 'eta': 0,
 'incidentid': '1593d050fe02a25164f12645faa88c6c',
 'incidentstatus': 'closed',
 'lastupdated': '2018-04-28 02:46:01.542604+05:30'}

其中lastupdated是一个字符串。

我尝试使用以下方法导入字符串:

x['lastupdated'].strptime(d, "%Y-%m-%d %H:%M:%S.%f")

我得到以下错误,因为我当然没有考虑时区偏移。

  

ValueError:未转换的数据仍为:+05:30

当我尝试添加%z时,我仍然会收到以下错误:

res['lastupdated'].strptime(d, "%Y-%m-%d %H:%M:%S.%f%z")
  

ValueError:时间数据'2018-06-15 02:23:22.681421 + 05:30'没有   匹配格式'%Y-%m-%d%H:%M:%S。%f%Z'

虽然dateutil.parse as an option works,但它会让事情变得复杂,因为现在我有两个时区库需要处理。

知道如何解决这个问题吗?

0 个答案:

没有答案