-3

Im trying to convert my time to a 12 hour with AM/PM but i keep getting an error and have no idea why. The context is taking the last number of minutes and figuring out what time that ends up being. Here is my code, if anyone could help. It would be wonderful

import numpy as np
import datetime
import time

cumulative_myList = np.cumsum(myList)
time_in_minutes = cumulative_myList[-1]
time_in_seconds = time_in_minutes*60

print(time_in_seconds)

time = datetime.timedelta(0,time_in_seconds)
print(time)

last_bus_time = time.strptime(time, "%H:%M")
last_bus_time.strftime("%I:%M %p")
smci
  • 32,567
  • 20
  • 113
  • 146
Lucas Brawdy
  • 49
  • 1
  • 6

2 Answers2

4

datetime.timedelta represents a duration, not a time of day. If you want to treat a duration as a time of day, you need to add it to a datetime object that contains the beginning of a day. So you can do:

time = datetime.datetime(2000, 1, 1) + datetime.timedelta(seconds = time_in_seconds)
print(time.strftime("%I:%M %p"))

The date 2000-01-01 is arbitrary, since we don't care what the date is, we just need one to get the time from it.

DEMO

See related: What is the standard way to add N seconds to datetime.time in Python?

Barmar
  • 741,623
  • 53
  • 500
  • 612
0

strptime is not a method of class datetime.timedelta.

You can check the available methods in the python3 datetime docs

You can also verify this from the repl:

>>> import datetime
>>> dt = datetime.datetime.now()
>>> type(dt)
<class 'datetime.datetime'>
>>> time = datetime.timedelta(0, 100)
>>> type(time)
<class 'datetime.timedelta'>

If your time in seconds is from midnight, then you can simply construct a datetime object and add on your time:

>>> import datetime
>>> dt = datetime.datetime.now()
>>> dt = dt.replace(hour=0, minute=0, second=0, microsecond=0)
>>> time = datetime.timedelta(0,time_in_seconds)
>>> last_bus_time = dt + time
>>> last_bus_time.strftime("%I:%M%p")
Thomas5631
  • 244
  • 1
  • 11