代码之家  ›  专栏  ›  技术社区  ›  Vishal

在datetime python中去掉秒

  •  40
  • Vishal  · 技术社区  · 16 年前

    现在我知道了

    datetime.datetime(2010, 7, 6, 5, 27, 23, 662390)
    

    我怎样才能得到公正 datetime.datetime(2010, 7, 6, 5, 27, 0, 0)

    3 回复  |  直到 16 年前
        1
  •  127
  •   ʇsәɹoɈ    11 年前
    dtwithoutseconds = dt.replace(second=0, microsecond=0)
    

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

        2
  •  22
  •   Trenton McKinney ivirshup    6 年前

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

    无需先创建datetime对象,然后再对其进行操作。

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

        3
  •  13
  •   Joseph Spiros    16 年前

    你可以用 datetime.replace 要获取不带秒和微秒的新datetime对象,请执行以下操作:

    the_time = datetime.now()
    the_time = the_time.replace(second=0, microsecond=0)
    
        4
  •  0
  •   HelloSam    5 年前

    有人说Python可能很快就会增加纳秒,如果是这样的话 replace(microsecond=0) 其他答案中提到的方法可能会失败。

    datetime.fromisoformat( datetime.now().isoformat(timespec='minutes') )
    

    也许这有点愚蠢和昂贵,通过字符串表示,但它给了我一个和平的心态。