Search code examples
pythondatetimemilliseconds

Python and Round Milliseconds in Datetime Object


Everywhere I look seems to do some sort of truncation on milliseconds after converting a datetime object to a string and then manipulating the string. I would like to round the milliseconds within a datetime object without converting it to a string - is this possible? For example, I have

datetime.datetime(2018, 2, 20, 14, 25, 43, 215000)

I would like this to be:

datetime.datetime(2018, 2, 20, 14, 25, 43, 200000)

I would also like this to be rounded appropriately meaning that if it was 249999 it would round downward to 200000 and if 250000 it would round upward to 300000. Help?


Solution

  • Here is a workflow:

    # Setting initial datetime
    In [116]: dt = datetime.datetime(2018, 2, 20, 14, 25, 43, 215000)
    
    In [117]: dt.microsecond
    Out[117]: 215000
    
    # Setting new microsecond value
    # You can add you logic here e.g. if you want to
    # convert to seconds and then check
    In [118]: new_ms = 200000 if dt.microsecond < 250000 else 300000
    
    # Replacing the old with the new value
    In [119]: new_dt = dt.replace(microsecond=new_ms)
    
    In [120]: new_dt
    Out[120]: datetime.datetime(2018, 2, 20, 14, 25, 43, 200000)
    

    Hope this will get you started.