【问题标题】:Using %f with strftime() in Python to get microseconds在 Python 中使用 %f 和 strftime() 来获得微秒
【发布时间】:2011-10-04 09:00:01
【问题描述】:

我正在尝试使用 strftime() 到微秒精度,这似乎可以使用 %f (如 here 所述)。但是,当我尝试以下代码时:

import time
import strftime from time

print strftime("%H:%M:%S.%f")

...我得到了小时、分钟和秒,但是 %f 打印为 %f,没有微秒的符号。我在 Ubuntu 上运行 Python 2.6.5,所以应该没问题,应该支持 %f(据我所知,它支持 2.6 及更高版本。)

【问题讨论】:

    标签: python time strftime


    【解决方案1】:

    使用 Python 的 time 模块,%f 无法获得微秒。

    对于那些仍然只想使用time 模块的人,这里有一个解决方法:

    now = time.time()
    mlsec = repr(now).split('.')[1][:3]
    print time.strftime("%Y-%m-%d %H:%M:%S.{} %Z".format(mlsec), time.localtime(now))
    

    您应该得到类似 2017-01-16 16:42:34.625 EET 的信息(是的,我使用毫秒,因为它已经足够了)。

    要将代码分解为详细信息,请将以下代码粘贴到 Python 控制台中:

    import time
    
    # Get current timestamp
    now = time.time()
    
    # Debug now
    now
    print now
    type(now)
    
    # Debug strf time
    struct_now = time.localtime(now)
    print struct_now
    type(struct_now)
    
    # Print nicely formatted date
    print time.strftime("%Y-%m-%d %H:%M:%S %Z", struct_now)
    
    # Get miliseconds
    mlsec = repr(now).split('.')[1][:3]
    print mlsec
    
    # Get your required timestamp string
    timestamp = time.strftime("%Y-%m-%d %H:%M:%S.{} %Z".format(mlsec), struct_now)
    print timestamp
    

    为澄清起见,我还将我的 Python 2.7.12 结果粘贴到此处:

    >>> import time
    >>> # get current timestamp
    ... now = time.time()
    >>> # debug now
    ... now
    1484578293.519106
    >>> print now
    1484578293.52
    >>> type(now)
    <type 'float'>
    >>> # debug strf time
    ... struct_now = time.localtime(now)
    >>> print struct_now
    time.struct_time(tm_year=2017, tm_mon=1, tm_mday=16, tm_hour=16, tm_min=51, tm_sec=33, tm_wday=0, tm_yday=16, tm_isdst=0)
    >>> type(struct_now)
    <type 'time.struct_time'>
    >>> # print nicely formatted date
    ... print time.strftime("%Y-%m-%d %H:%M:%S %Z", struct_now)
    2017-01-16 16:51:33 EET
    >>> # get miliseconds
    ... mlsec = repr(now).split('.')[1][:3]
    >>> print mlsec
    519
    >>> # get your required timestamp string
    ... timestamp = time.strftime("%Y-%m-%d %H:%M:%S.{} %Z".format(mlsec), struct_now)
    >>> print timestamp
    2017-01-16 16:51:33.519 EET
    >>>
    

    【讨论】:

      【解决方案2】:

      当微秒的“%f”不起作用时,请使用以下方法:

      import datetime
      
      def getTimeStamp():
          dt = datetime.datetime.now()
          return dt.strftime("%Y%j%H%M%S") + str(dt.microsecond)
      

      【讨论】:

      • 如果 dt.microsecond 少于 6 位,这将不起作用。
      • 这是唯一对我有用的解决方案。在 Windows 上的 Jython 中,%f 似乎总是打印文字 %f。我想要毫秒,所以使用 str(dt.microsecond)[0:3]
      • str(dt.microsecond)[0:3] 可能会产生错误的结果(例如,300 微秒是 0.300 毫秒,但它会打印 300!)
      • "%03d"%int(dt.microsecond/1000) -> 这会打印毫秒而不是微秒
      【解决方案3】:

      如果你想要速度,试试这个:

      def _timestamp(prec=0):
          t = time.time()
          s = time.strftime("%H:%M:%S", time.localtime(t))
          if prec > 0:
              s += ("%.9f" % (t % 1,))[1:2+prec]
          return s
      

      prec 是精确度——你想要多少个小数位。 请注意,该函数不存在小数部分前导零的问题,就像此处介绍的其他一些解决方案一样。

      【讨论】:

        【解决方案4】:

        如果你想要一个整数,试试这个代码:

        import datetime
        print(datetime.datetime.now().strftime("%s%f")[:13])
        

        输出:

        1545474382803
        

        【讨论】:

          【解决方案5】:

          您可以使用 datetime 的 strftime 函数来获取它。问题是时间的 strftime 接受一个不携带微秒信息的时间元组。

          from datetime import datetime
          datetime.now().strftime("%H:%M:%S.%f")
          

          应该做的伎俩!

          【讨论】:

          • 如果你想使用%z就不行
          • @Vallentin 很确定情况正好相反! datetimesupports the %z directivetime doesn't appear to
          • 在 Python 3 中都支持 %z :-) here's datetime 然后是 time
          • 哦,你是对的。我在日期时间错过了它,因为它不在底部,就像在桌子上一样。 :P
          • 请注意from datetime import datetime。如果你只是做import datetime,你将不得不使用datetime.datetime.now().strftime("%H:%M:%S.%f")
          【解决方案6】:

          这应该做的工作

          import datetime
          datetime.datetime.now().strftime("%H:%M:%S.%f")
          

          它会打印出来

          HH:MM:SS.microseconds 像这样,例如14:38:19.425961

          【讨论】:

            【解决方案7】:

            您正在查看错误的文档。 time 模块 has different documentation

            您可以像这样使用datetime 模块strftime

            >>> from datetime import datetime
            >>>
            >>> now = datetime.now()
            >>> now.strftime("%H:%M:%S.%f")
            '12:19:40.948000'
            

            【讨论】:

            【解决方案8】:

            您还可以使用 time 模块的 time() 函数获得微秒精度。
            time.time() 以秒为单位返回纪元以来的时间。它的小数部分是以微秒为单位的时间,这是你想要的。)

            >>> from time import time
            >>> time()
            ... 1310554308.287459   # the fractional part is what you want.
            
            
            # comparision with strftime -
            >>> from datetime import datetime
            >>> from time import time
            >>> datetime.now().strftime("%f"), time()
            ... ('287389', 1310554310.287459)
            

            【讨论】:

            • 优秀。感谢你的帮助。我已经设法让事情正常进行,尽管发现了一个奇怪的错误,这意味着在特定 cset 上以 sudo 身份运行脚本时不会出现微秒,但是如果我在尝试在特定 cset 上运行它之前以 sudo 身份登录,则可以这样做。奇数。
            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2018-10-11
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2022-10-19
            相关资源
            最近更新 更多