Sarada Akurathi
Sarada Akurathi

Reputation: 1188

How to convert date before 1970 in python

I wrote a method to handle mongodb result, where date is coming as datetime.datetime() i used dumps method, which converts the date is not milliseconds, here if the date is before 1970 then date is converted to negative value and i am unable to handle this to change back to date and time after wards.

My sample code is as below:

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

sample input data can be as

MongoResult: {'profileDetails': {'basicDetails': {'dateOfBirth': {'$date': -414892800000L}, 'customerCode': 'C017145'}, 'xDirLevel': {'masterCode': 1}, 'createdDate': {'$date': 1467392480962L}}, '_id': {'$oid': '58872e98321a0c863329199d'}}
Key: profileDetails.basicDetails.dateOfBirth.$date

I am getting error ValueError: timestamp out of range for platform localtime()/gmtime() function if the date is before 1970, how to handle this

Upvotes: 2

Views: 5214

Answers (1)

Sarada Akurathi
Sarada Akurathi

Reputation: 1188

I got the solution for date convertion before 1970 as below:

need to replace the code in if((string.find(key,"$date"))>=0): block as

 ndate = datetime.datetime(1970, 1, 1) + datetime.timedelta(seconds=(returnValue)/1000)
returnValue  = str(ndate).replace(' ','T')

I got the solution from the another question in stackoverflow Timestamp out of range for platform localtime()/gmtime() function

Upvotes: 1

Related Questions