如何一致地打印时间增量(即格式化)

问题描述 投票:0回答:1

我有这段代码可以打印以毫秒为单位的时间差。

#!/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')

它打印出这个,没有一致性

$ python ./prntdatetest.py

0:00:00.002000 0:00:00 -1 天,23:59:59.995000

我想要这样打印

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

我不想使用 print 但我想使用 stdout.write

我该怎么做?

python datetime printing timedelta
1个回答
0
投票

如果总是只有毫秒,你可以定义一个格式函数:

def format_diff(diff):
    return f'0:00:00.{diff.microseconds//1000:03d}'

如果需要 >= 1 秒的值,则:

def format_diff(diff):
    return f'{diff.seconds//60//60:02d}:{diff.seconds//60:02d}:{diff.total_seconds()%60:02.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')

输出

00:00:0.002 00:00:0.000 23:1439:59.995
© www.soinside.com 2019 - 2024. All rights reserved.