S Kal
S Kal

Reputation: 37

How to extract time and store in an Array/Structure

I want to measure the time difference between two time readings in a Python script.

time_stamp_1 = datetime.datetime.now()
# some task
time_stamp_2 = datetime.datetime.now()

time_stamp = time_stamp_2 - time_stamp_1

time_stamp_sec = ??

I got the result as 0:00:04.052000.

  1. What exactly is this time format I am getting?

  2. How to extract the time in seconds from time_stamp?

  3. How to store time_stamp in an array like variable (as I want to use a loop and store the time_stamp for each loop)

  4. How to store time_stamp_sec in an array like variable

Upvotes: 1

Views: 710

Answers (1)

Simeon Visser
Simeon Visser

Reputation: 122376

1) It's a datetime.timedelta object which is being printed nicely:

>>> import datetime
>>> datetime.timedelta(days=3)
datetime.timedelta(3)
>>> print(datetime.timedelta(days=3))
3 days, 0:00:00
>>> print(datetime.timedelta(hours=3))
3:00:00

2) You can use total_seconds():

>>> t = datetime.timedelta(hours=3)
>>> t.total_seconds()
10800.0

This gives you a float as the datetime.timedelta may represent an amount of time which isn't an exact number of seconds.

3) You can append it to a list at each step in the loop:

>>> d = []
>>> d.append(t)
>>> d
[datetime.timedelta(0, 10800)]

4) You can do the same with the result of total_seconds():

>>> e = []
>>> e.append(t.total_seconds())
>>> e
[10800.0]

Upvotes: 1

Related Questions