Python中如何分割字符串提取ISO格式日期的年月日部分
实现方法
你拿到的接口返回时间是标准ISO 8601格式,字符串中固定用T作为日期段和时间段的分隔符,直接做字符串分割取前缀即可得到目标日期,不需要额外依赖第三方库。
最简实现(推荐)
纯字符串操作,无额外依赖,不会出现时区转换导致的日期偏差,修改后完整代码如下:
@client.command() async def userjoindate(ctx, username): user = await roblox.get_user_by_username(username) response = requests.get(f'https://users.roblox.com/v1/users/{user.id}') json_data = json.loads(response.text) message = json_data['created'].split('T')[0] await ctx.send(message)
可扩展实现(适合后续时间处理场景)
如果后续需要做注册时长计算、不同日期格式转换等操作,可以用Python内置的datetime库解析时间后格式化输出:
from datetime import datetime @client.command() async def userjoindate(ctx, username): user = await roblox.get_user_by_username(username) response = requests.get(f'https://users.roblox.com/v1/users/{user.id}') json_data = json.loads(response.text) # 解析UTC时区的ISO格式时间 create_time = datetime.fromisoformat(json_data['created'].replace('Z', '+00:00')) # 格式化输出年-月-日格式 message = create_time.strftime('%Y-%m-%d') await ctx.send(message)
注意:如果直接用字符串分割的方案,不要用截取固定长度字符串的方式(比如
[:10]),按T分割的兼容性更强,哪怕后续接口返回的时间精度变化也不会出问题。
内容的提问来源于stack exchange,提问作者Ocryol
相关产品推荐
相关产品推荐

