没有熊猫,无法将字符串转换为json中的datetime对象?

时间:2020-10-22 17:26:34

标签: python datetime

我有一个json,其中时间位于字段“ createdAt”中。 'createdAt': '2020-10-17T02:56:51+0900'

我想解析时间(它是一个字符串)并将其转换为datetime对象,但是我不明白为什么我的代码没有采用指定的datetime格式,而是返回所有我的createdAt time与0

for line in data:
    try:
        date_time_str = line['createdAt']
        date_time_obj = datetime.strptime(f'{str(date_time_str)}', "%Y-%m-%dT%H:%M:%S%z")
        line['createdAt'] = date_time_obj
    except ValueError:
        line['createdAt'] = 0

注意:不允许使用dateutil

1 个答案:

答案 0 :(得分:1)

你为什么不这样做呢?

from datetime import datetime

data = [
    {"title": "First title", "createdAt": "2020-10-19T02:56:51+0000", "text": "Some post content", "author": "ninja"},
    {"title": "Second title", "createdAt": "2020-10-19T02:56:51+0000", "text": "Some post content", "author": "ninja"},
    {"title": "Third title", "createdAt": "2020-10-19T02:56:51+0000", "text": "Some post content", "author": "ninja"},
]

for item in data:
    try:
        item['createdAt'] = datetime.strptime(item['createdAt'], "%Y-%m-%dT%H:%M:%S%z")
    except ValueError:
        item['createdAt'] = ""

print(data)
print(data[0]['createdAt'])

哪个给你:

[{'title': 'First title', 'createdAt': datetime.datetime(2020, 10, 19, 2, 56, 51, tzinfo=datetime.timezone.utc), 'text': 'Some post content', 'author': 'ninja'}, {'title': 'Second title', 'createdAt': datetime.datetime(2020, 10, 19, 2, 56, 51, tzinfo=datetime.timezone.utc), 'text': 'Some post content', 'author': 'ninja'}, {'title': 'Third title', 'createdAt': datetime.datetime(2020, 10, 19, 2, 56, 51, tzinfo=datetime.timezone.utc), 'text': 'Some post content', 'author': 'ninja'}]
2020-10-19 02:56:51+00:00

有趣的事实:

没有使用dateutil