Skip to main content
 首页 » 编程设计

python之如何强制日期时间在 python 中保留 0 微秒

2025年01月19日13shanyou

我需要一个日期时间来保留微秒,即使它们为 0。这是一个示例:

from datetime import datetime 
starttime = datetime(year=2018, month=2, day=15, hour=8, minute=0, second=0, microsecond=0) 
print(starttime.isoformat()) 

我希望以 00.000000 秒打印。但它以 0 秒打印。如果我输入 1 微秒,那么它将打印 00.000001。

问题是我使用的 jquery 调用需要 iso 格式,在秒位置有一个 float 。

请您参考如下方法:

你可以用strftime手动格式化:

>>> starttime = datetime(year=2018, month=2, day=15, hour=8, minute=0, second=0, microsecond=0) 
>>> starttime.strftime("%Y-%m-%dT%H:%M:%S.%f") 
'2018-02-15T08:00:00.000000' 

对比:

>>> starttime.isoformat() 
'2018-02-15T08:00:00' 

和:

>>> starttime = datetime(year=2018, month=2, day=15, hour=8, minute=0, second=0, microsecond=1) 
>>> starttime.strftime("%Y-%m-%dT%H:%M:%S.%f") 
'2018-02-15T08:00:00.000001' 
>>> starttime.isoformat() 
'2018-02-15T08:00:00.000001'