简体   繁体   English

用format()打印numpy timedelta64

[英]printing numpy timedelta64 with format()

I would like to print a numpy.timedelta64() value in a formatted way. 我想以格式化的方式打印numpy.timedelta64()值。 The direct method works well: 直接方法效果很好:

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

Which I guess comes from the __str__ () method 我猜这来自__str__ ()方法

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

But when I try to print it with the format() function I get the following error: 但是,当我尝试使用format()函数打印它时,出现以下错误:

>>> 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

I would like to understand the underlying mechanism of the "string".format() function, and why it doesn't work in this particular case. 我想了解“ string” .format()函数的基本机制,以及为什么在这种特殊情况下它不起作用。

According to the 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. 通常, 格式化值的工作是通过值本身的__format __()方法完成的。 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. 通过在调用__format __()之前将值转换为字符串,可以绕过常规的格式化逻辑。

>>> 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

By appending !s conversion flag , you can force it to use str : 通过添加!s转换标志 ,可以强制其使用str

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

falsetru mentions one aspect of the problem. falsetru提到了问题的一方面。 The other is why this errors at all. 另一个就是为什么这个错误。

Looking at the code for __format__ , we see that it is a generic implementation. 查看__format__的代码 ,我们看到它是一个通用实现。

The important part is: 重要的部分是:

    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
    }

This triggers, and tries to run: 这将触发并尝试运行:

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

but Numpy (rightly) says that you can't convert a number with units to a raw number. 但是Numpy(正确地)说您不能将带有单位的数字转换为原始数字。

This looks like a bug. 这看起来像个错误。

%s should be fine. %s应该可以。 It calls str() on the object. 它在对象上调用str()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM