Home > database >  I need to append dates into one list in Python
I need to append dates into one list in Python

Time:09-15

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

CodePudding user response:

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)

CodePudding user response:

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)
  • Related