简体   繁体   中英

can't convert string to datetime object in a json, without pandas?

i have a json where the time is located in the field 'createdAt'. 'createdAt': '2020-10-17T02:56:51+0900'

I want to parse the time (which is a string) and convert it into a datetime object, but I'm not why my code isn't picking up on the specified datetime format and is returning all my createdAt times with 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

note: not allowed to use dateutil

Why don't you just do this?

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'])

Which gives you:

[{'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

Fun fact:

No dateutil used!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM