首页 > 解决方案 > 从 requests.get 映射日期时间转换

问题描述

from datetime import datetime

date = "24.03.2021 15:35:20"  # type datetime
birthday = "19.12.1990"  # type date


def convert(data, type):
    if type == "datetime":
        data = datetime.strptime(data, "%d.%m.%Y %H:%M:%S")
        timestamp = datetime.timestamp(data)
        return timestamp
    elif type == "date":
        data = datetime.strptime(data, "%d.%m.%Y")
        timestamp = datetime.timestamp(data)
        return timestamp

    return None


recorded_date = convert(date, "datetime")
recorded_birthday = convert(birthday, "date")

data = {
    "date": {"value": "recorded_date", "type": "datetime"},
    "firstname": {"value": "John", "type": "string"},
    "last_name": {"value": "Doe", "type": "string"},
    "birthday": {"value": "recorded_birthday", "type": "date"},
}

# save data to database with api requests(json) without type like {'date': recorded_date, 'firstname': 'John',...}


# retrive data from database with api requests(json)
newdata = requests.get(url)
print(newdata.json())
# {'date': 1616589320.0, 'firstname': 'John', 'last_name': 'Doe', 'birthday': 661554000.0}

如您所见,我的数据很好,但我需要从时间戳转换回日期时间或字符串,但我有很多数据,所以我不知道要转换的字段,因为我不再有类型我想要这个输出

# {'date': 24.03.2021 15:35:20, 'firstname': 'John', 'last_name': 'Doe', 'birthday': 19.12.1990}

有什么想法吗?这个怎么做?最后我不知道我的数据它可以是任何东西所以它必须是一般的有人可以添加生日另一个可以添加周年纪念这是一个大型数据库所以我不想检查我的所有字段

问题是不知道我的字典的键它可以是任何东西

标签: pythonjsondatetime

解决方案


您可以使用datetime.fromtimestamp将时间戳字符串解析为日期时间。您可以重写您的convert函数以将其标记为您想要转换回日期时间的内容。试试下面的代码:

from datetime import datetime

def convert(data, type):
    if type == "datetime":
        data = datetime.strptime(data, "%d.%m.%Y %H:%M:%S")
        timestamp = datetime.timestamp(data)
        return 'd'+str(timestamp)
    elif type == "date":
        data = datetime.strptime(data, "%d.%m.%Y")
        timestamp = datetime.timestamp(data)
        return 'd'+str(timestamp)

    return None


recorded_date = convert(date, "datetime")
recorded_birthday = convert(birthday, "date")


newdata = requests.get(url)
serialized = newdata.json() # convert to dict
for key in serialized:
    # if it's in format 'd12314151231' ('d' in front of a timestamp)
    if serialized[key][0] == 'd' and serialized[key][1].isnumeric():
        serialized[key] = datetime.fromtimestamp(serialized[key])

这将转换serialized['date']serialized['birthday']日期时间对象。


推荐阅读