Search code examples
pythondatetimeprintingtimedelta

How to print timedelta consistently (i.e. formatted)


I have this code that prints the time difference in milliseconds.

#!/usr/bin/python
import datetime
import sys

date1= datetime.datetime.strptime('20231107-08:52:53.539', '%Y%m%d-%H:%M:%S.%f')
date2= datetime.datetime.strptime('20231107-08:52:53.537', '%Y%m%d-%H:%M:%S.%f')
diff = date1-date2
sys.stdout.write(str(diff) + '\t')
date1= datetime.datetime.strptime('20231107-08:52:53.537', '%Y%m%d-%H:%M:%S.%f')
date2= datetime.datetime.strptime('20231107-08:52:53.537', '%Y%m%d-%H:%M:%S.%f')
diff = date1-date2
sys.stdout.write(str(diff) + '\t')
date1= datetime.datetime.strptime('20231107-08:52:53.532', '%Y%m%d-%H:%M:%S.%f')
date2= datetime.datetime.strptime('20231107-08:52:53.537', '%Y%m%d-%H:%M:%S.%f')
diff = date1-date2
sys.stdout.write(str(diff) + '\n')

And it prints this, without consistency

$ python ./prntdatetest.py

0:00:00.002000 <tab> 0:00:00 <tab> -1 day, 23:59:59.995000

I want this to be printed like this

00:00:00.002 <tab> 00:00:00.000 <tab> -0:00:00.005

I do not want to use the print but i want to use stdout.write

How can I do this?


Solution

  • You can define the following formatting function:

    def format_diff(diff):
        sign = '-' if diff < datetime.timedelta(0) else ''
        seconds = abs(diff.total_seconds())
        return f'{sign}{seconds//60//60:02.0f}:{seconds//60%60:02.0f}:{seconds%60:06.03f}'
    
    #!/usr/bin/python
    import datetime
    import sys
    
    date1= datetime.datetime.strptime('20231107-08:52:53.539', '%Y%m%d-%H:%M:%S.%f')
    date2= datetime.datetime.strptime('20231107-08:52:53.537', '%Y%m%d-%H:%M:%S.%f')
    diff = date1-date2
    sys.stdout.write(format_diff(diff) + '\t')
    date1= datetime.datetime.strptime('20231107-08:52:53.537', '%Y%m%d-%H:%M:%S.%f')
    date2= datetime.datetime.strptime('20231107-08:52:53.537', '%Y%m%d-%H:%M:%S.%f')
    diff = date1-date2
    sys.stdout.write(format_diff(diff) + '\t')
    date1= datetime.datetime.strptime('20231107-08:52:53.532', '%Y%m%d-%H:%M:%S.%f')
    date2= datetime.datetime.strptime('20231107-08:52:53.537', '%Y%m%d-%H:%M:%S.%f')
    diff = date1-date2
    sys.stdout.write(format_diff(diff) + '\n')
    

    Output:

    00:00:00.002    00:00:00.000    -00:00:00.005
    

    Note: that handles values up to on day. For >= 1 day deltas, you need to update the function.