如何在python中转换1970年以前的日期

2024-10-03 06:21:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我写了一个处理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年,如何处理


Tags: tokeyimportjsonformatdatetimedatestring
1条回答
网友
1楼 · 发布于 2024-10-03 06:21:55

我得到了1970年以前日期转换的解决方案如下:

需要将if((string.find(key,"$date"))>=0):块中的代码替换为

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

我从stackoverflowTimestamp out of range for platform localtime()/gmtime() function中的另一个问题得到了解决方案

相关问题 更多 >