1

I currently have the following where the AllergiesList can be one or more dicts.

{
  "AllergiesList": [
    {
      "Date": "2021-09-03T00:00:00",
      "Description": "string",
      "Source": "string",
      "Severity": "string",
      "Reaction": "string",
      "TypeCode": "string",
      "Notes": "string",
      "Notes1": "string",
      "TenancyDescription": "string"
    }
  ],
  "TotalItemCount": 0
}

My question is how would I format the Date key within all dictionaries to be in a specific format e.g. d/m/Y

I currently have the following to remove dicts that are more than X months old

def is_recent(entry,amount):
    limit_time = pd.Timestamp.today() - relativedelta.relativedelta(months=amount)
    return pd.to_datetime(entry["Date"]) > limit_time

Used as follows:

allergies = session["allergies"] # This is the same as the code snippet above i.e. a list of dictionaries
session["allergies"] = [entry for entry in allergies["AllergiesList"] if is_recent(entry,6)]

Would I need to do another def() or can my current one be amended to do what's needed?

pee2pee
  • 3,619
  • 7
  • 52
  • 133
  • 1
    Why do this with `pandas`? – I'mahdi Jun 23 '22 at 08:14
  • `session["allergies"]` is a list of dicts like the one you posted? – timgeb Jun 23 '22 at 08:15
  • @timgeb That is correct – pee2pee Jun 23 '22 at 08:15
  • @I'mahdi because that was the highest upvoted answer given to me previously on another question – pee2pee Jun 23 '22 at 08:16
  • If you are not otherwise using `pandas` it's an overkill - just use datetime module – buran Jun 23 '22 at 08:18
  • Then I don't quite get what the problem is, since you seem to have basic programming knowledge. `for dict_ in something['AllergiesList']: dict_['Date'] = algorithm(dict_['Date'])`? – timgeb Jun 23 '22 at 08:18
  • Does this answer your question? [Parse date string and change format](https://stackoverflow.com/questions/2265357/parse-date-string-and-change-format) – buran Jun 23 '22 at 08:18
  • @timgeb it was more whether I could incorporate it into my existing `def` or not – pee2pee Jun 23 '22 at 08:20
  • yes you can add more code to functions (?!) – timgeb Jun 23 '22 at 08:21
  • Wow! You can? Amazing. I knew StackOverflow would be really helpful today. Thanks. I mean, the question was how I would do that but here we are... – pee2pee Jun 23 '22 at 08:24
  • With regards to finding recent dates - check https://stackoverflow.com/q/37385078/4046632 or work with `datetime.timedelta` – buran Jun 23 '22 at 08:32
  • That's not what I am asking – pee2pee Jun 23 '22 at 08:34
  • I know - you are asking about changing string format and I already suggested a dupe for that. Mu second comment was related to your use of pandas for something that can be done easily without it. Take it or leave it - it's up to you. – buran Jun 23 '22 at 08:37
  • The question was how I'd integrate it into my list comprehension mostly – pee2pee Jun 23 '22 at 08:39
  • You need to write a function that will take a dict as argument, modify the str and return the new dict. Your current one cannot serve that purpose if you want to use list comprehension. However, you can modify your current function and turn it into generator that will take a list of dicts and yield only recent dicts, after it modify them. – buran Jun 23 '22 at 08:43

3 Answers3

1

just replace is_recent function with following one

import datetime 

def is_recent(entry, amount):
    limit_time = datetime.datetime.now() - datetime.timedelta(months=amount)
    return datetime.datetime.strptime(entry["Date"], '%Y-%m-%dT%H:%M:%S') > limit_time
nilbarde
  • 331
  • 1
  • 3
1
from datetime import datetime

rec_list = {
    "AllergiesList": [
        {
            "Date": "2021-09-03T00:00:00",
            "Description": "string",
            "Source": "string",
            "Severity": "string",
            "Reaction": "string",
            "TypeCode": "string",
            "Notes": "string",
            "Notes1": "string",
            "TenancyDescription": "string"
        },
        {
            "Date": "2021-09-09T00:00:00",
            "Description": "string",
            "Source": "string",
            "Severity": "string",
            "Reaction": "string",
            "TypeCode": "string",
            "Notes": "string",
            "Notes1": "string",
            "TenancyDescription": "string"
        }
    ],
    "TotalItemCount": 0
}

for rec in rec_list["AllergiesList"]:
    rec["Date"] = datetime.strptime(rec["Date"], "%Y-%m-%dT%H:%M:%S").strftime("%d/%m/%Y")

print(rec_list)

Using above code snippet you can convert your all date format records as per your requirment.

Output:-

{
    "AllergiesList": [
        {
            "Date": "03/09/2021",
            "Description": "string",
            "Source": "string",
            "Severity": "string",
            "Reaction": "string",
            "TypeCode": "string",
            "Notes": "string",
            "Notes1": "string",
            "TenancyDescription": "string",
        },
        {
            "Date": "09/09/2021",
            "Description": "string",
            "Source": "string",
            "Severity": "string",
            "Reaction": "string",
            "TypeCode": "string",
            "Notes": "string",
            "Notes1": "string",
            "TenancyDescription": "string",
        },
    ],
    "TotalItemCount": 0,
}

Thanks :)

Devbrat Shukla
  • 504
  • 4
  • 11
0

Try the code below, it will convert the given format to DD/MM/YYYY

from datetime import datetime

date_time_str = entry['Date']
date_time_obj = datetime.strptime(date_time_str, '%Y-%m-%dT%H:%M:%S')
date = date_time_obj.strftime("%d/%m/%Y")
print('Date String:', date)

If you want DD/MM/YY format replace %Y with %y in date_time_obj.strftime("%d/%m/%Y")

Sidharth Mudgil
  • 1,293
  • 8
  • 25