python - 从 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}
有什么想法吗?这个怎么做?最后我不知道我的数据它可以是任何东西所以它必须是一般的有人可以添加生日另一个可以添加周年纪念这是一个大型数据库所以我不想检查我的所有字段
问题是不知道我的字典的键它可以是任何东西
解决方案
您可以使用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']
日期时间对象。
推荐阅读
- asp.net - Cookie 在 HTTPS 连接中是否标记为安全?
- python - 将 API 响应转换为 Pandas DataFrame
- javascript - 我怎样才能从这个 JS 对象中取出这个属性?
- javascript - JavaScript 和 Python 中的模不匹配
- html - 带有媒体查询的页面预览
- powerbi - 筛选未连接的 2 个表但与另一个表连接
- amazon-web-services - 适用于 Spring Boot 的 AWS SES 电子邮件接收开发工具包
- typescript - '无法读取 null 的属性'addEventListener''firebase auth
- python - XGBoost 在创建 XGBoost.DMatrix 时杀死内核
- google-cloud-firestore - Firestore安全规则中的数据验证,如果未知数据则拒绝