我有一段代码,用于打印两个时间之间的毫秒差。但是,输出的时间格式并不符合我的期望,我希望得到一个统一且易读的格式。以下是原始代码及其输出:
#!/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 day, 23:59:59.995000
而我期望的输出格式是:
00:00:00.002 00:00:00.000 -0:00:00.005
为了实现这个目标,并且坚持使用sys.stdout.write
而非print
函数,我应该如何调整代码呢?