简体   繁体   中英

How to replace a specific character in a python dictionary value

I am creating a python dictionary item from a json response while loop but I would like to replace certain characters in the dictionary value as I have a datetime value being returned but this value has undesirable characters in there.

eg my dictionary for a datetime response is returning a value key pair of "created_at":"2019-10-11T23:57:34Z". I would like to replace the 'T' character and the 'Z' character in the response with a space instead of the 'T' and nothing for the 'Z'.

Here is my code that generates the ticket_search dictionary:

ticket_search = []
   url = 'https://myzendeskinstance.zendesk.com/api/v2/search.json? 
   query=type:ticket created>2019-10-11'
   while url:
      response = session.get(url)
      if response.status_code != 200:
         print('Error with status code {}'.format(response.status_code))
         exit()
   data = response.json()
   ticket_search.extend(data['results'])
   url = data['next_page']

ticketsearch[created_at] returns the value of '2019-10-11T23:57:34Z' (just an example of a output row) where I would like it to be '2019-10-11 23:57:34'

import datetime
ticketsearch= "2019-10-11T23:57:34Z"
response= datetime.datetime.strptime(f'{ticketsearch}', '%Y-%m-%dT%H:%M:%SZ')
new_Date = response .strftime('%Y-%m-%d %H:%M:%S')

I believe it can be achieved in many ways like:

1:

response = "2019-10-11T23:57:34Z"
response = response.replace('T', ' ')
response = response.replace('Z', '')
# output: 2019-10-11 23:57:34

2:

response = "2019-10-11T23:57:34Z"
avoidList = ['T', 'Z']

for char in response:
    if char in avoidList:
        response = (response.replace(char, ' ').strip())
# output: 2019-10-11 23:57:34

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