2014-10-27 103 views
1

我使用下面的打印出來的時間戳:格式微秒到小數點後兩位(其實轉換毫秒到幾十微秒)

strftime('%d-%m-%Y %H:%M:%S.%f') 

但是我想在微秒四捨五入到小數點後兩位,而不是打印小數點後六位。是否有一種更簡單的方法來實現這一點,而不是將所有時間元素「解包」,格式化並將微秒舍入到2位小數,並格式化新的「打印字符串」?

+0

這些是'datetime'實例? – 2014-10-27 11:52:55

回答

0
decimal_places = 2 
ndigits = decimal_places - 6 
assert ndigits < 0 
d = d.replace(microsecond=round(d.microsecond, ndigits)) 
print(d.strftime('%d-%m-%Y %H:%M:%S.%f')[:ndigits]) 
# -> 2014-10-27 11:59:53.87 
2

你必須自己動手;使用字符串格式化來格式化不微秒的日期,然後添加在單獨的microsecond屬性的頂部有兩個數字:

'{:%d-%m-%Y %H:%M:%S}.{:02.0f}'.format(dt, dt.microsecond/10000.0) 

演示:

>>> from datetime import datetime 
>>> dt = datetime.now() 
>>> '{:%d-%m-%Y %H:%M:%S}.{:02.0f}'.format(dt, dt.microsecond/10000.0) 
'27-10-2014 11:56:32.72' 
+0

已經這樣做了。因爲float會成爲datetime()的有用補充,所以不禁感覺秒。 – MichaelJohn 2014-11-04 12:36:22