Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I have this code into a class that get a string, my goal is parse the string , do some adjusts to get a valid datetime format from the string.

An input string for this function could be = "A0X031716506774"

import datetime
def _eventdatetime(self, string):
    base_date = datetime.datetime.strptime("1980-1-6 0:0", "%Y-%m-%d %H:%M")
    weeks = datetime.timedelta(weeks = int(string[5:9]))
    days = datetime.timedelta(days = int(string[9]))
    seconds = datetime.timedelta(seconds = int(string[10:15]))
    stamp = base_date + weeks + days + seconds

    adjustUTC = datetime.timedelta(hours = 3) 
    stamp =  stamp - adjustUTC

    return str(stamp)

Total time: 0.0483931 s, how can I improve the perfomance for this? The third line seems to be the slowest...

Thanks in advance...

share|improve this question
add comment

1 Answer

up vote 2 down vote accepted
import datetime
def _eventdatetime(self, string):
    base_date = datetime.datetime.strptime("1980-1-6 0:0", "%Y-%m-%d %H:%M")

Why are you specifying the date as a string only to parse it? Just do: base_date = datetime.datetime(1980,1,6,0,0). You should also make it a global constant so as not to recreate it all the time.

    weeks = datetime.timedelta(weeks = int(string[5:9]))
    days = datetime.timedelta(days = int(string[9]))
    seconds = datetime.timedelta(seconds = int(string[10:15]))

There is no need to create several timedelta objects, you can do datetime.timedelta(weeks = ..., days = ..., seconds = ...)

    stamp = base_date + weeks + days + seconds

    adjustUTC = datetime.timedelta(hours = 3) 
    stamp =  stamp - adjustUTC

I'd use stamp -= datetime.timedelta(hours = 3) # adjust for UTC

    return str(stamp)
share|improve this answer
    
Thanks for your time Winston! Your advise is very useful. –  cespinoza Jan 16 '13 at 19:10
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.