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

Python如何为未设置秒和微秒的datetime对象补充对应参数?

解决方法

你可以直接用datetime对象内置的replace()方法修改秒和微秒字段,该方法不会改动原始对象,会返回调整字段后的新datetime对象,未指定的原有字段(年、月、日、时、分、时区)都会完整保留。

示例代码

import datetime

# 原始datetime对象
dt = datetime.datetime(2021, 10, 15, 0, 0, tzinfo=datetime.timezone.utc)

# 按需求填入对应的秒、微秒数值,这里以你给出的示例值21秒、436248微秒为例
dt_updated = dt.replace(second=21, microsecond=436248)

如果你需要用当前UTC时间的秒和微秒来填充,可以用以下写法:

import datetime

dt = datetime.datetime(2021, 10, 15, 0, 0, tzinfo=datetime.timezone.utc)
current_utc = datetime.datetime.now(datetime.timezone.utc)
dt_updated = dt.replace(second=current_utc.second, microsecond=current_utc.microsecond)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 22:24:04