我写了一个处理mongodb结果的方法,其中date是以datetime.datetime()
的形式出现的,我使用了dumps
方法,它将日期转换为毫秒,这里如果日期在1970年之前,则日期将被转换为负值,我无法处理此问题,无法将其改回wards之后的日期和时间。在
我的示例代码如下:
import datetime
from bson.json_util import dumps
from bson.objectid import ObjectId
import string
def get_json_key_value(mongoResult, key):
# converts mongoResult which is not into proper json format to proper json format
result = dumps(dict(eval(mongoResult)))
# convert unicode format to string format
data = __convert(dict(eval(result)))
# code to get the json value.
value="data"
jsonlist = key.split('.')
for eachKey in jsonlist:
if (eachKey.isdigit()):
value = value + "["+eachKey+ "]"
else:
value = value + "['"+eachKey + "']"
returnValue = eval(value)
#processing the date value, if key has $date
if((string.find(key,"$date"))>=0):
returnValue = datetime.datetime.fromtimestamp(returnValue/1000.0)
returnValue = datetime.datetime.strftime(returnValue , format="%Y-%m-%dT%H:%M:%S")
returnValue = datetime.datetime.strptime(str(returnValue), "%Y-%m-%dT%H:%M:%S")
returnValue = returnValue - datetime.timedelta(minutes=330)
returnValue = datetime.datetime.strftime(returnValue , format="%Y-%m-%dT%H:%M:%S")
return returnValue
样本输入数据可以是
^{pr2}$我收到错误ValueError: timestamp out of range for platform localtime()/gmtime() function
如果日期早于1970年,如何处理
我得到了1970年以前日期转换的解决方案如下:
需要将
if((string.find(key,"$date"))>=0):
块中的代码替换为我从stackoverflowTimestamp out of range for platform localtime()/gmtime() function中的另一个问题得到了解决方案
相关问题 更多 >
编程相关推荐