如何舍入 Python 中的日期时间变量?

How to round a datetime variable in Python?

如何舍入像这样的 datetime 变量:

x = datetime.now()

产生这样的东西:

2022-05-04 15:36:01.055696

像这样?

2022-05-04 15:36:01.057

如果您只想删除最后几个字符,您可以这样做:

print(x.strftime('%Y-%m-%d %H:%M:%S.%f')[:-3])

格式化 str 是您在输出中看到的默认值

您可以将其转换为unix时间戳,然后将数字四舍五入到小数点后3位。

from datetime import datetime

x = '2022-05-04 15:36:01.055696'

# Convert to datetime object
d = datetime.strptime(x, '%Y-%m-%d %H:%M:%S.%f')

# Convert to rounded unix timestamp
ts = datetime.fromtimestamp(round(d.timestamp(), 3))

# You know have rounded datetime object, you can convert back to string with
ts.strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]

Pandas 时间戳为此内置了 in-function。 将时间戳设为时间戳对象,然后使用 round.

import pandas as pd

x = '2022-05-04 15:36:01.055696'
ts = pd.Timestamp(x)
ts_rounded = ts.round(freq='L')
print(ts_rounded) 2022-05-04 15:36:01.056000

如果你想修改一个datetime对象,你可以舍入它的.microsecond属性:

x = datetime.now()
print(x.isoformat(' '))
# 2022-05-04 15:36:01.055696

x = x.replace(microsecond=round(x.microsecond / 1000) * 1000)
print(x.isoformat(' '))
# 2022-05-04 15:36:01.056

在任何情况下(即使不修改对象和舍入微秒),要获得您想要的表示形式,您可以使用适当的方法对其进行格式化:

x.isoformat(' ', timespec='milliseconds')
# 2022-05-04 15:36:01.056

请注意,使用 round(x.microsecond / 1000) * 1000 修改对象的微秒数会将它们 四舍五入 到最接近的毫秒。如果您只想 截断 微秒,请使用 x.microsecond // 1000 * 1000.