【问题标题】:Mapping for datetime conversion from requests.get从 requests.get 映射日期时间转换
【发布时间】:2021-03-25 14:04:34
【问题描述】:
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}

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

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

【问题讨论】:

    标签: python json datetime


    【解决方案1】:

    您可以使用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'] 转换为日期时间对象。

    【讨论】:

    • 问题是不知道我的字典的键,它可以是任何东西
    • @AliMertcanTekin 这些时间戳会是字典中唯一的整数吗?
    • 很遗憾没有
    • @AliMertcanTekin 我刚刚进行的编辑可能会有所帮助。
    • 我无法将它设为我的日期时间,因为在数据库中我无法进行搜索或比较,感谢您的回答
    猜你喜欢
    • 2021-12-31
    • 1970-01-01
    • 2016-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多