剥离datetime python中的秒数

Vis*_*hal 43 python

now()给了我

datetime.datetime(2010, 7, 6, 5, 27, 23, 662390)
Run Code Online (Sandbox Code Playgroud)

我如何得到datetime.datetime(2010, 7, 6, 5, 27, 0, 0)(datetime对象)几分钟后的所有内容为零?

ʇsә*_*ɹoɈ 97

dtwithoutseconds = dt.replace(second=0, microsecond=0)
Run Code Online (Sandbox Code Playgroud)

http://docs.python.org/library/datetime.html#datetime.datetime.replace

  • 请注意,这只是一个值,并且不会改变dt - 如果这是你想要的,那么也将它分配回dt. (11认同)

use*_*924 15

我知道这是一个很老的问题,但到目前为止我还没有找到任何真正完整的答案.

首先不需要创建日期时间对象并随后对其进行操作.

dt = datetime.now().replace(second = 0,microsecond = 0)

将返回所需的对象


Jos*_*ros 13

您可以使用datetime.replace获取没有秒和微秒的新datetime对象:

the_time = datetime.now()
the_time = the_time.replace(second=0, microsecond=0)
Run Code Online (Sandbox Code Playgroud)

  • 或者`the_time = datetime.now().replace(second = 0,microsecond = 0)` (6认同)