converting time data which is saved as a string to an integer in seconds [duplicate]

Multi tool use


converting time data which is saved as a string to an integer in seconds [duplicate]
This question already has an answer here:
I have some time data that I read into a numpy array as a string. It's in the format
x = ['11:13:01.337 AM', '11:13:03.337 AM', '11:13:05.337 AM']
I want to be able to plot this cleanly over an indefinite amount of time, let's say the data goes for 4 hours. How can I convert this into a reasonable form to plot? I am not sure what form would be best so suggestions would be helpful. As you can probably tell I'm a noob, my boss and I appreciate the help!
This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.
1 Answer
1
Unlike time.strptime
, datetime.strptime
can parse such strings, including microseconds, and you can convert the result to a number (seconds since midnight):
time.strptime
datetime.strptime
import datetime
def parse(s):
d = datetime.datetime.strptime(s, "%I:%M:%S.%f %p")
return 3600 * d.hour + 60 * d.minute + d.second + d.microsecond * 1e-6
And use it like this:
x = ['11:13:01.337 AM', '11:13:03.337 AM', '11:13:05.337 AM']
print([parse(s) for s in x])
This should be safe even in the presence of DST changes because strptime merely parses the time, and does not attempt any such semantic conversions
Eihm5bwng1K,18xA7MoADkLLB6Ss5ArCZY BRCfms5Zou8vslCcqDj Nd 8,tW5QdlCdwjnCI9 W2SLfZm3Ly5hh M9aj8AoZ1u7lAq
it works! thank you
– trey
yesterday