2014-09-25 191 views
2

我想以格式化的方式打印numpy.timedelta64()值。直接法效果很好:打印numpy timedelta64與格式()

>>> import numpy as np 
>>> print np.timedelta64(10,'m') 
10 minutes 

我的猜測來自於__str__()方法

>>> np.timedelta64(10,'m').__str__() 
'10 minutes' 

但是,當我嘗試與格式()函數,我得到以下錯誤打印:

>>> print "my delta is : {delta}".format(delta=np.timedelta64(10,'m')) 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
TypeError: don't know how to convert scalar number to long 

我想了解「string」.format()函數的基本機制,以及爲什麼它在這種情況下不起作用。

回答

2

falsetru提到了問題的一個方面。另一個是爲什麼這個錯誤。

看着the code for __format__,我們看到它是一個通用的實現。

最重要的部分是:

else if (PyArray_IsScalar(self, Integer)) { 
#if defined(NPY_PY3K) 
     obj = Py_TYPE(self)->tp_as_number->nb_int(self); 
#else 
     obj = Py_TYPE(self)->tp_as_number->nb_long(self); 
#endif 
    } 

這將觸發,並嘗試運行:

int(numpy.timedelta64(10, "m")) 

但numpy的(正確地)說,你不能將一些與單位原始數。

這看起來像一個錯誤。

+0

你認爲我應該在某處提交錯誤報告嗎? – 2014-09-25 17:33:34

+0

[我剛剛爲你做了。](https://github.com/numpy/numpy/issues/5121) – Veedrac 2014-09-25 17:33:45

1

%s應該沒問題。它在對象上調用str()

3

按照Format String Syntax documentation

The conversion field causes a type coercion before formatting. Normally, the job of formatting a value is done by the __format__() method of the value itself. However, in some cases it is desirable to force a type to be formatted as a string, overriding its own definition of formatting. By converting the value to a string before calling __format__(), the normal formatting logic is bypassed.

>>> np.timedelta64(10,'m').__format__('') 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
TypeError: don't know how to convert scalar number to long 

通過追加!s conversion flag,你可以強制使用str

>>> "my delta is : {delta!s}".format(delta=np.timedelta64(10,'m')) 
'my delta is : 10 minutes' 
+1

謝謝你的解決方案,我現在在我的代碼中使用它,但我選擇了Veedrac的答案,以便走向失敗的線路並指出潛在的錯誤。 – 2014-09-25 17:45:41