如何替换 python 字典值中的特定字符
How to replace a specific character in a python dictionary value
我正在从 json 响应 while 循环创建一个 python 字典项,但我想替换字典值中的某些字符,因为我有一个返回的日期时间值,但这个值有那里有不受欢迎的角色。
例如我的日期时间响应字典正在返回值键对 "created_at":“2019-10-11T23:57:34Z”。我想将响应中的 'T' 字符和 'Z' 字符替换为 space 而不是 'T' 并且 'Z' 没有任何内容。
这是我生成 ticket_search 字典的代码:
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 '2019-10-11T23:57:34Z' 的值(只是输出行的一个示例)我希望它是'2019-10-11 23:57:34'
我相信可以通过多种方式实现,例如:
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
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')
我正在从 json 响应 while 循环创建一个 python 字典项,但我想替换字典值中的某些字符,因为我有一个返回的日期时间值,但这个值有那里有不受欢迎的角色。
例如我的日期时间响应字典正在返回值键对 "created_at":“2019-10-11T23:57:34Z”。我想将响应中的 'T' 字符和 'Z' 字符替换为 space 而不是 'T' 并且 'Z' 没有任何内容。
这是我生成 ticket_search 字典的代码:
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 '2019-10-11T23:57:34Z' 的值(只是输出行的一个示例)我希望它是'2019-10-11 23:57:34'
我相信可以通过多种方式实现,例如:
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
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')