Python - time difference in milliseconds not working for me

前端 未结 5 2096
野性不改
野性不改 2020-12-05 22:51

I\'ve read a few posts about this and thought I had some code that worked. If the difference between the 2 values is less than a 1sec then the millisecs displayed is correct

相关标签:
5条回答
  • 2020-12-05 23:14

    Try using total_seconds method:

    print time_diff_wind.total_seconds() * 1000
    

    That method is equivalent to: (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6

    Note: It's available since version 2.7

    0 讨论(0)
  • 2020-12-05 23:18
    >>> a = datetime.datetime.now()
    >>> b = datetime.datetime.now()
    >>> a
    datetime.datetime(2013, 8, 25, 2, 5, 1, 879000)
    >>> b
    datetime.datetime(2013, 8, 25, 2, 5, 8, 984000)
    >>> a - b
    datetime.timedelta(-1, 86392, 895000)
    >>> b - a
    datetime.timedelta(0, 7, 105000)
    >>> (b - a).microseconds
    105000
    >>> (b - a).seconds
    7
    >>> (b - a).microseconds / 1000
    105
    

    your microseconds don't include the seconds that have passed

    0 讨论(0)
  • 2020-12-05 23:24

    I faced this issue as well, but in my case I need real milliseconds precision, so using total_seconds() * 1000 isn't an option for me, so what I did is:

    def millis_interval(start, end):
        """start and end are datetime instances"""
        diff = end - start
        millis = diff.days * 24 * 60 * 60 * 1000
        millis += diff.seconds * 1000
        millis += diff.microseconds / 1000
        return millis
    

    I hope this helps someone else! :)

    0 讨论(0)
  • 2020-12-05 23:29

    From the documentation:

    Instance attributes (read-only):

    Attribute Value

    days Between -999999999 and 999999999 inclusive

    seconds Between 0 and 86399 inclusive

    microseconds Between 0 and 999999 inclusive

    Microseconds never exceed 999,999. Hence your milliseconds never exceed 999.

    0 讨论(0)
  • 2020-12-05 23:38

    The correct answer (in 2020) is:

    >>> from datetime import timedelta
    >>> timedelta(days=1, milliseconds=50) / timedelta(milliseconds=1)
    86400050.0
    

    The other answers lose precision and/or are more verbose.

    0 讨论(0)
提交回复
热议问题