Home > other >  Pyton - strftime' requires a 'datetime.date' but received a 'datetime.time'
Pyton - strftime' requires a 'datetime.date' but received a 'datetime.time'

Time:12-22

I am trying to get a list of all the TimeFrames that are unique in my dataset. My dataset has a lot of measurements that according to the year that I am studying has different time measurements. For instance, in 2021 the measurements are made every 15 minutes and in 2020 It was every 20 minutes. As I want to compare the measurement disregarding the date, caring only about the time, I am trying to get a list of the TimeFrames in the Dataset. This is what I have so far:

Data['Date | Hour'] = pd.to_datetime(Data['Date'], format='%Y-%m-%d %H:%M')
Data = Data.set_index((Data['Date | Hour']))
Data['Hour']=Data.index.time
Data['Date']=Data.index.date
TimeFrames=[]
V=Data['Hour'].unique()
a=np.arange(0,len(V))
for i in a:
    TimeFrames.append(datetime.strftime(V[i],'%H:%M:%S'))

It should result in something like:

TimeFrames=['00:00:00','00:15:00','00:30:00','00:45:00' ...

However, it results in:

TypeError: descriptor 'strftime' requires a 'datetime.date' object but received a 'datetime.time'

I tried to do it with the date (V=Data[‘Date’].unique()) and it worked resulting in a list of dates… I was thinking that maybe I could just add a random date to V, run the for cycle and after getting the list delete the date from all the strings resulting in the list that I want but that would be my last option.. any ideas??

CodePudding user response:

Note that strftime is available as a method of the classes datetime.datetime, datetime.date and datetime.time (see also documentation on datetime module), and you are dealing with a datetime.time object here.

So you should be fine by changing your last line to something like

time.strftime(V[i],'%H:%M:%S')

which calls the correct one of the three methods (of course you must import the class using from datetime import time).

To make it even shorter, you can iterate directly over the array (no need for V and a):

for v in Data['Hour'].unique():
    TimeFrames.append(time.strftime(v,'%H:%M:%S'))
  • Related