如何在python中转换1970年以前的日期
问题描述:
我写了一个方法来处理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年以前,如何处理这种
答
我在1970年之前得到了日期转换的解决方案,如下所示:
需要if((string.find(key,"$date"))>=0):
块以替换代码
ndate = datetime.datetime(1970, 1, 1) + datetime.timedelta(seconds=(returnValue)/1000)
returnValue = str(ndate).replace(' ','T')
我从另一个问题的解决方案计算器Timestamp out of range for platform localtime()/gmtime() function