You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何生成带3位毫秒与UTC偏移的Python datetime格式化结果

实现3位毫秒+UTC偏移日期字符串的方法

不需要绕路先转成自定义格式再做strptime解析,直接用以下方案即可,不会出现截断时区的问题:

方案1:Python 3.11+ 原生支持(最简便)

Python 3.11 版本为isoformat()新增了timespec参数,直接指定输出精度为毫秒即可一步得到结果:

import datetime
now = datetime.datetime.now(datetime.timezone.utc)
created = now.isoformat(timespec='milliseconds')

输出结果完全匹配要求格式:

'2022-06-27T14:51:23.230+00:00'

timespec='milliseconds'会自动保留3位毫秒值,同时完整保留UTC偏移部分,不需要手动做任何字符串处理。

方案2:全版本兼容方案

如果使用3.11以下的Python版本,不要直接对完整字符串做尾部切片,通过拆分字符串的方式精准截断毫秒部分即可:

import datetime
now = datetime.datetime.now(datetime.timezone.utc)
raw_iso = now.isoformat()
# 以小数点为界拆分,前半段是日期+秒的整数部分,后半段包含微秒和时区
date_section, remain_section = raw_iso.split('.')
# 后半段前3位是毫秒值,第6位之后是完整的UTC偏移
millisecond = remain_section[:3]
timezone = remain_section[6:]
created = f"{date_section}.{millisecond}{timezone}"

这个方案的逻辑是固定的:isoformat输出中,小数点后固定先跟6位微秒,再跟时区字符串,所以偏移量不会被误截断,在所有Python3版本上都能稳定运行。

也可以通过提前截断微秒值的方式实现,逻辑更直观:

import datetime
now = datetime.datetime.now(datetime.timezone.utc)
# 微秒转毫秒后取整,丢弃后3位精度
now = now.replace(microsecond=now.microsecond // 1000 * 1000)
# 截断后微秒固定为整千值,直接拆分拼接即可
created = now.isoformat()[:-9] + now.isoformat()[-6:]

直接切片出错的原因

默认isoformat输出的末尾6位是固定格式的UTC偏移(如+00:00共6个字符),直接对整个字符串做[:-3]截断会刚好切掉偏移的后半段,才会得到+00这类错误结果。

内容的提问来源于stack exchange,提问作者PloniStacker

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.28 10:36:23