0

I'm trying to convert timesteps of 2 min to datetime format. I want to do it for a full day, so from 0 min to 1440 min in steps of 2 min.

My problem is that when I convert 0 seconds to datetime it outputs 01:00:00, when I want 00:00:00. Here's the code (len(df.index) = 720, it comes from a dataset I have of those 720 timesteps):

from datetime import datetime

timeline = []
for timestep in range(len(df.index)):
    time = datetime.fromtimestamp(timestep*2*60).strftime("%H:%M:%S")
    timeline.append(time)
print(timeline[:5])

And the output is. Any idea why?

['01:00:00', '01:02:00', '01:04:00', '01:06:00', '01:08:00']
Joan E.
  • 5
  • 2
  • This is what you need? https://stackoverflow.com/questions/9744775/how-to-convert-integer-timestamp-to-python-datetime – briba May 06 '20 at 11:45

1 Answers1

0

A datetime is a full date and time, like May 6, 2020 7:23PM, but you're looking for a time period - a timedelta:

from datetime import timedelta

timeline = []
for timestep in range(len(df.index)):
    time = timedelta(seconds=timestep)
    timeline.append(time)

Then you can convert each timedelta object to a string HH:MM:SS:

>>> str(timedelta(seconds=0))
'0:00:00'
>>> str(timedelta(seconds=60))
'0:01:00'
>>> str(timedelta(seconds=65))
'0:01:05'
ForceBru
  • 43,482
  • 10
  • 63
  • 98