saga
saga

Reputation: 755

Is there a faster way to change and parse date time for comparison on python?

If I have 2 sets of date time data. The time interval of the first set is 1 hour, and the second set is 4 hour. This is based on candlestick data, for instance, 4 hour candle open time = 05:00, close time = 09:00. I need to find the corresponding candle on 1 hour, to match with the one on 4 hour. If the candles are based on close time, I just need to find the date time 09:00 for both 1 hour and 4 hour, simple and easy.

But since the candles are based on open time, if I need the same candle, I have to look for 05:00 on 4 hour, and the corresponding (candle or time) is 08:00 on 1 hour. Basically I need to convert them to close time for matching like this:

from dateutil.relativedelta import *

if 1H+relativedelta(hour=+1) = 4H+relativedelta(hour=+4):

The above is what I researched online, but this method is very slow for looping the data. My friend used PHP and it could be done fast. Does anyone know a faster way to do it on Python? Thanks.

Upvotes: 0

Views: 223

Answers (1)

Heath Raftery
Heath Raftery

Reputation: 4169

I can't see how relativedelta is useful. timedelta is more natural. It's going to be hard to be much faster than this:

import datetime

oneHourStart = datetime.datetime(2018,1,16,8,0,0)
fourHourStart = datetime.datetime(2018,1,16,5,0,0)
oneHourDelta = datetime.timedelta(hours=1)
fourHourDelta = datetime.timedelta(hours=4)

if oneHourStart+oneHourDelta == fourHourStart+fourHourDelta:
    print("Match")

Output:

Match

Upvotes: 1

Related Questions