【发布时间】:2020-11-17 08:01:49
【问题描述】:
我有如下形状的日期时间数据:
yyyy-mm-dd hh:minmin:secsec + hh:minmin
比如这个:2020-02-01 01:00:00+01:00
我现在想将其转换为浮点数。我使用了我找到这个问题的解决方案的功能:python datetime to float with millisecond precision
def datetime_to_float(d):
return d.timestamp()
我使用以下代码将此函数应用于我的日期时间对象:
time_in_float = []
for i in time:
time_in_float.append(i.datetime_to_float())
得到了这个错误:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-11-f6272033e480> in <module>()
2
3 for i in time:
----> 4 time_in_float.append(i.datetime_to_float())
5
AttributeError: 'datetime.datetime' object has no attribute 'datetime_to_float'
我需要在这里改变什么?
非常感谢!
【问题讨论】:
-
什么是
time?正如@leuchtum 回答的那样,你调用你的函数就好像它是一个类的方法,这在这里似乎不适用。 -
time是一个包含我所有日期时间对象的列表。 -
定义函数不会向
datetime类添加方法。无论如何,您根本不需要该功能。将time_in_float.append(i.datetime_to_float())更改为time_in_float.append(i.timestamp())。 -
为什么不直接
time_in_float = [t.timestamp() for t in time]?
标签: python datetime error-handling