J-Jillu
J-Jillu

Reputation: 65

Datetime formatting

The api I am working with gives time is the following format when I place an order.

'orderDateTime': '12-May-2020 14:54:11'

What I am looking to do is to find the number of minutes/seconds that have passed since I placed the order. So if it has already been for example 10 minutes, if I would like to cancel or modify the order I can do it.

I have tried everything I know to convert the given time format to do what I want but have been unsuccessful. Please help. Thanks in advance.

time_now = datetime.now() print("Time now is",time_now) t1 = time_now.strftime("%d-%b-%Y %H:%M:%S") print(t1) trade_time = datetime(12-May-2020 15:01:32) t2 = datetime.strftime(trade_time,"%d-%b-%Y %H:%M:%S") print(t2)

Upvotes: 1

Views: 49

Answers (1)

Thierry Lathuille
Thierry Lathuille

Reputation: 24288

You are mixing the datetime objects and their representation as strings.

What you need to do is convert your trade time to a datetime object, by using the strptime method. strftime does the opposite, it produces a formatted text representation of your datetime.

Then, you can subtract the two datetime objects, which will give you the difference as a timedelta, from which you can get the difference as a number of seconds.

So, your code should look like:

from datetime import datetime

time_now = datetime.now()

trade_time_as_str = '12-May-2020 15:01:32'
trade_time = datetime.strptime(trade_time_as_str,"%d-%b-%Y %H:%M:%S")

elapsed = time_now - trade_time
elapsed_seconds = elapsed.total_seconds()

print(elapsed_seconds)
# 15808.77104

Upvotes: 1

Related Questions