Nepura
Nepura

Reputation: 125

Convert a pandas Timestamp list

In my variable 'Datelist3' there is a pandas Timestamp list, in the following format:

[Timestamp('2019-12-04 09:00:00+0100', tz='Europe/Rome'), Timestamp('2019-12-04 09:30:00+0100', tz='Europe/Rome'), ....]

I'm having difficulty converting this list to a datetime string list, in this format:

['2019-12-04 09:00:00', '2019-12-04 09:30:00', .....]

I did these tests:

Datelist3.to_datetime # -> error: 'list' object has no attribute 'to_datetime'
Datelist3.dt.to_datetime # -> error: 'list' object has no attribute 'dt'
Datelist3.to_pydatetime() # -> error: 'list' object has no attribute 'to_pydatetime()'
Datelist3.dt.to_pydatetime() # -> error: 'list' object has no attribute 'dt'

I got to the variable 'Datelist3' with the following statement:

Datelist3 = quoteIntraPlot.index.tolist()

If I this instruction changes it to:

Datelist3 = quoteIntraPlot.index.strftime("%Y-%m-%d %H:%M:%S").tolist()

That's exactly what I want to achieve. The problem is that out of 10 times, 6-7 times is ok and 3-4 times it gives me an error: " 'Index' object has no 'strftime' ". It's very strange. How could I solve this problem?

Upvotes: 3

Views: 2105

Answers (1)

Vincent
Vincent

Reputation: 1604

If your data is well formed, this would work :

time_list = [Timestamp('2019-12-04 09:00:00+0100', tz='Europe/Rome'), Timestamp('2019-12-04 09:30:00+0100', tz='Europe/Rome'), ....]
str_list = [t.strftime("%Y-%m-%d %H:%M:%S") for t in time_list]

However, if you face the same error as before, it means that not all your index are timestamps. In this case, you need to clean your data first.

Upvotes: 3

Related Questions