Home > Mobile >  Python: Format datetime string in a list of dictionaries
Python: Format datetime string in a list of dictionaries

Time:06-25

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?

CodePudding user response:

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 :)

CodePudding user response:

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")

CodePudding user response:

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