0

I have datetime data which is of the following shape:

yyyy-mm-dd hh:minmin:secsec + hh:minmin

For example this one: 2020-02-01 01:00:00+01:00

I now would like to convert it to float. I used the function I found the solution of this question: python datetime to float with millisecond precision

def datetime_to_float(d):
    return d.timestamp()

I applied this function to my datetime-object with this code:

time_in_float = []

for i in time:
    time_in_float.append(i.datetime_to_float())

And got this error:

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

What do I have to change here?

Thanks a lot!

Tobitor
  • 1,388
  • 1
  • 23
  • 58
  • 1
    what is `time`? and as @leuchtum answered, you call your function as if it was a method of a class, which seems not applicable here. – FObersteiner Nov 17 '20 at 08:04
  • `time`is a list with all my datetime object. – Tobitor Nov 17 '20 at 08:08
  • 1
    Defining a function doesn't add a method to the `datetime` class. You don't need that function at all, anyway. Change `time_in_float.append(i.datetime_to_float())` to `time_in_float.append(i.timestamp())`. – BoarGules Nov 17 '20 at 08:14
  • 1
    why not simply `time_in_float = [t.timestamp() for t in time]`? – FObersteiner Nov 17 '20 at 08:14

2 Answers2

2

you need to do time_in_float.append(datetime_to_float(i)) in your loop

leuchtum
  • 71
  • 2
1

you define a function, you need to pass your datetime.datetime object as argument and not expect to apply the function as method

def datetime_to_float(d):
    return d.timestamp()


time_in_float = []

for i in time:
    time_in_float.append(datetime_to_float(i))

However there is no need to define a function that will only make your code more obscure, so this should be just fine:

time_in_float = []

for i in time:
    time_in_float.append(i.timestamp())

or even list comprehension

time_in_float = [(i.timestamp() for i in time]

all this assumes i is datetime.datetimeobject and notstr`

buran
  • 13,682
  • 10
  • 36
  • 61