Datetime对象中的Python和Round Milliseconds

时间:2018-02-20 23:37:39

标签: python datetime milliseconds

在将datetime对象转换为字符串然后操纵字符串之后,我看起来似乎在几毫秒内进行某种截断。我想在datetime对象中舍入毫秒而不将其转换为字符串 - 这可能吗?例如,我有

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

我希望如此:

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

我还希望这个被适当地舍入,这意味着如果它是249999它将向下舍入到200000并且如果250000它将向上舍入到300000.帮助?

1 个答案:

答案 0 :(得分:1)

这是一个工作流程:

# 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)

希望这会让你开始。