0
我寫了一個方法來處理mongodb的結果,其中日期爲datetime.datetime()
我使用dumps
方法,它轉換的日期不是毫秒,這裏如果日期在1970年之前,那麼日期轉換爲負值,我無法處理這個變化回到病房後的日期和時間。如何在python中轉換1970年以前的日期
我的示例代碼如下:
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
樣本輸入數據可以作爲
MongoResult: {'profileDetails': {'basicDetails': {'dateOfBirth': {'$date': -414892800000L}, 'customerCode': 'C017145'}, 'xDirLevel': {'masterCode': 1}, 'createdDate': {'$date': 1467392480962L}}, '_id': {'$oid': '58872e98321a0c863329199d'}}
Key: profileDetails.basicDetails.dateOfBirth.$date
我收到錯誤ValueError: timestamp out of range for platform localtime()/gmtime() function
如果日期是1970年以前,如何處理這種