简体   繁体   中英

I need to append dates into one list in Python

I have strings looks like JSONs. if I print the type of them the output will be str .

{"date": "2022-09-14 15:22:53.084456"}
{"date": "2022-09-14 11:37:33.753514"}

I did convert them into real JSONs. Using this: i = json.loads(i)

Now print(i) will output this:

{'date': '2022-09-14 11:37:33.753514'}

And print(type(i)) will output this:

<class 'dict'>

And print(type(i['date'])) will output this:

<class 'str'>

Now convert it to real date, and append the dates to a list dates :

date = datetime.strptime(i['date'], '%Y-%m-%d %H:%M:%S.%f')
if date > datetime.now() - timedelta(hours=24):
    dates = []
    dates.append(date)
    if len(dates) > 0:
        print(len(dates))

Output:

1
[datetime.datetime(2022, 9, 14, 10, 56, 36, 284933)]
1
[datetime.datetime(2022, 9, 14, 11, 37, 33, 753514)]

The problem here I'm appending them to a list, But instead of adding all the dates into one list. it's creating a list for each date.

Wanted result:

print(len(dates))
2

Let's invent some code that will (hopefully) enlighten you:

from datetime import datetime, timedelta
# a dictionary containing some date/time values as strings
JSON = {"dates": ["2022-09-14 10:56:36.284933", "2022-09-13 10:56:36.200000"]}
# a list of dates
dates = []
# iterate over the dates in the dictionary
for ds in JSON["dates"]:
    # convert to a datetime object
    date = datetime.strptime(ds, '%Y-%m-%d %H:%M:%S.%f')
    # check range
    if date > datetime.now()-timedelta(hours=24):
        # append to the list
        dates.append(date)
# print the list
print(dates)

It is not clear how you obtain the date variable, but every time it has a new value, you need to append it to the list:

dates = []
dates.append(date)

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