Python 和 Datetime 对象中的舍入毫秒数

Python and Round Milliseconds in Datetime Object

在将日期时间对象转换为字符串然后处理该字符串后,我所看到的任何地方似乎都在毫秒内进行了某种截断。我想舍入 datetime 对象中的毫秒而不将其转换为字符串 - 这可能吗?例如,我有

datetime.datetime(2018, 2, 20, 14, 25, 43, 215000)

我希望这样:

datetime.datetime(2018, 2, 20, 14, 25, 43, 200000)

我也希望它能适当地四舍五入,这意味着如果它是 249999,它会向下舍入到 200000,如果是 250000,它会向上舍入到 300000。帮助?

这是一个工作流程:

# Setting initial datetime
In [116]: dt = datetime.datetime(2018, 2, 20, 14, 25, 43, 215000)

In [117]: dt.microsecond
Out[117]: 215000

# Setting new microsecond value
# You can add you logic here e.g. if you want to
# convert to seconds and then check
In [118]: new_ms = 200000 if dt.microsecond < 250000 else 300000

# Replacing the old with the new value
In [119]: new_dt = dt.replace(microsecond=new_ms)

In [120]: new_dt
Out[120]: datetime.datetime(2018, 2, 20, 14, 25, 43, 200000)

希望这能让你入门。