python - 基本的 Python JSON 日期时间转换问题

标签 python json datetime

我是一名 Python 初学者,遇到了一个问题。尝试提取 API 信息并将提取的 JSON 时间对象转换为 Python 中的日期时间对象,以便我最终可以在其上运行 date.weekday() 函数(总体目标是从 API 中提取所有日期并查看哪个输出按天数-我计划在提取所有日期后填充一个空字典)。

出于某种原因,即使使用我的条件语句,我仍在打印 (2015, 04, 06) 全为零。那是我的问题。

我有一种感觉,我遇到了一些基本错误,而且还有一种比在日期对象中使用 0 填充来执行所有 ifs/elses 更好的方法。

到目前为止,这是我的代码:

from datetime import date
import datetime
import json
import requests

r = requests.get('https://api.github.com/repos/mbostock/d3/commits?since=2015-04-12330:00:000')
jsonoutput = r.json()
modified = (jsonoutput[0]["commit"]["author"]["date"])
#at this point, modified gives something like: "2015-04-06T22:28:16Z"

if modified[5] == 0:
    if modified[8] == 0:
        new_format = ("(" + modified[0:4] + ", " + modified[6] + ", " + modified[9] + ")")
        #with the particular jsonoutput[0] pulled here, this one should be triggered
    else:
        new_format = ("(" + modified[0:4] + ", " + modified[6] + ", " + modified[8:10] + ")")

else:
    if modified[8] == 0:
        new_format = ("(" + modified[0:4] + ", " + modified[5:7] + ", " + modified[9] + ")")
    else:
        new_format = ("(" + modified[0:4] + ", " + modified[5:7] + ", " + modified[8:10] + ")")

print(new_format)

print(date.weekday(datetime.date(new_format)))

最佳答案

错误发生在您当前的代码中,因为 new_format 被定义为字符串,而 datetime.date 将参数作为整数。此外,由于您将字符串 "0" 与数字 0 进行比较,因此根本不会创建修改后的内容。

取而代之的是:

new_format = ("(" + modified[0:4] + ", " + modified[6] + ", " + modified[8:10]) + ")")

这样做:

new_format = (int(modified[0:4]), int(modified[5:7]), int(modified[8:10]))

以上内容适用于您的所有情况,因此您也可以删除复杂的 if-else block 。

或者,您可以用 "T" 拆分这个修改后的字符串,然后使用另一个用 "-" 拆分来获取整数值:

new_format = map(int, modified.split("T")[0].split("-"))

作为参数传递时,您还需要解压缩列表,因此您的完整代码变为:

import json
import requests
from datetime import date

r = requests.get('https://api.github.com/repos/mbostock/d3/commits?since=2015-04-12330:00:000')
jsonoutput = r.json()
modified = jsonoutput[0]["commit"]["author"]["date"]
new_format = (int(modified[0:4]), int(modified[5:7]), int(modified[8:10]))
print(date.weekday(date(*new_format)))

此外,正如其他人已经在他们的回答中指出的那样,dateutil.parser.parse 可能比编写您自己的解析逻辑更好。 (dateutil 不是内置包,您必须安装它):)

关于python - 基本的 Python JSON 日期时间转换问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29737541/

相关文章:

json - 如何从以数字而不是字符串开头的 JSON 字典正确创建对象?

python-3.x - 如何用其他内容替换数据帧列的每个 "elements"的一部分

dataframe - 我可以使用 DataFrames 在 Julia 中按天或按月分组吗

java - 在java中将字符串转换为日期时间

python - 如何从以前的 celery 任务中产生 celery 任务?

python - Webdriver phantomjs 不再跟随点击链接

python - __init__ 形式 Django 中的查询集

python - 如何使用feature hasher将非数值型离散数据进行转换,以便传递给SVM?

java - 如何使用正则表达式修改其中的几个字段来创建新的 JSON 字符串?

android - 发送带有参数的 JSON 对象时出现 JSON 解析错误