0

I'm having a list with multiple timestamps in the form of 2021-04-13 11:03:13+02:00.

Now I wanted to use them, however I get the error ValueError: could not convert string to float.

Is there a way for me to turn them into a proper float value, without losing the actual date and time values?

Zerox
  • 290
  • 4
  • 18
  • 2
    Which float did you expect to get in this example? – mkrieger1 May 17 '21 at 07:22
  • 2
    I don't know if I understood your question right but I am working with a pandas dataframe and when trying to use the timestamp it tells me, that apparently he needs it in float format. And since I want to use the timestamps as a label for a model, they should keep their "value" while being converted to a float. – Zerox May 17 '21 at 07:24
  • 1
    Does this answer your question? [How to convert a string with timezone to unix timestamp python?](https://stackoverflow.com/questions/63722086/how-to-convert-a-string-with-timezone-to-unix-timestamp-python) – mkrieger1 May 17 '21 at 08:23
  • Thank you! This looks very promising. And how would I apply this conversion to every timestamp in the entire column? – Zerox May 17 '21 at 08:50
  • Maybe by writing a loop? – mkrieger1 May 17 '21 at 08:51

2 Answers2

1

Something like this... you will have to change the "%d/%m/%Y" pattern

import time
import datetime
  
  
string = "20/01/2020"
print(time.mktime(datetime.datetime.strptime(string,
                                             "%d/%m/%Y").timetuple()))
J.Stange
  • 478
  • 3
  • 8
0
2021-04-13 11:03:13+02:00

This does looks like ISO format, you might use datetime.datetime.fromisoformat to convert it to datetime object i.e.:

import datetime
stamp = "2021-04-13 11:03:13+02:00"
dt = datetime.datetime.fromisoformat(stamp)
print(dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second)

output

2021 4 13 11 3 13

Note that your stamp beyond date and time is holding time-offset (timezone) data (+02:00). If you want to turn such stamp into float you must to decide how to deal with time offsets.

Daweo
  • 31,313
  • 3
  • 12
  • 25