2014-09-25 195 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