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

如何在python中强制datetime保留0微秒

  •  3
  • Murenrb  · 技术社区  · 8 年前

    我需要一个datetime来保留微秒,即使它们是0。以下是一个示例:

    from datetime import datetime
    starttime = datetime(year=2018, month=2, day=15, hour=8, minute=0, second=0, microsecond=0)
    print(starttime.isoformat())
    

    我想把它打印出来 00.000000 几秒钟。但它是用 0 几秒钟。如果我输入1微秒,它就会打印出来 00.000001 .

    问题是我正在使用一个jquery调用,该调用需要iso格式,并且在秒位置有一个浮点数。

    3 回复  |  直到 8 年前
        1
  •  2
  •   juanpa.arrivillaga    8 年前

    您可以使用手动设置格式 strftime :

    >>> starttime = datetime(year=2018, month=2, day=15, hour=8, minute=0, second=0, microsecond=0)
    >>> starttime.strftime("%Y-%m-%dT%H:%M:%S.%f")
    '2018-02-15T08:00:00.000000'
    

    Vs:

    >>> starttime.isoformat()
    '2018-02-15T08:00:00'
    

    以及:

    >>> starttime = datetime(year=2018, month=2, day=15, hour=8, minute=0, second=0, microsecond=1)
    >>> starttime.strftime("%Y-%m-%dT%H:%M:%S.%f")
    '2018-02-15T08:00:00.000001'
    >>> starttime.isoformat()
    '2018-02-15T08:00:00.000001'
    
        2
  •  2
  •   evandrix    5 年前

    (确认在Python3.6之后工作,在2.7上不工作)

    isoformat() 接受参数:

    datetime.datetime(2020, 2, 20, 0, 0, 0, 0).isoformat(timespec='microseconds')
    Out[17]: '2020-02-20T00:00:00.000000'
    

    可能的值:

        'auto': the default behaviour
        'hours': '{:02d}'
        'minutes': '{:02d}:{:02d}'
        'seconds': '{:02d}:{:02d}:{:02d}'
        'milliseconds': '{:02d}:{:02d}:{:02d}.{:03d}'
        'microseconds': '{:02d}:{:02d}:{:02d}.{:06d}'
    
        3
  •  0
  •   Stephen Rauch Afsar Ali    8 年前

    只需对标准字符串转换进行少量操作,即可完成以下操作:

    代码:

    def force_microseconds(a_datetime):
        dt_str = a_datetime.isoformat()
        if '.' not in dt_str:
            dt_str += '.000000'
        return dt_str
    

    测试代码:

    import datetime as dt
    
    starttime = dt.datetime(year=2018, month=2, day=15, hour=8,
                            minute=0, second=0, microsecond=0)
    
    print(force_microseconds(starttime))
    print(force_microseconds(starttime + dt.timedelta(microseconds=1) ))
    

    结果:

    2018-02-15T08:00:00.000000
    2018-02-15T08:00:00.000001