I have this code in a class that gets a string, parses it, and makes some adjustments 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 performance for this? The third line seems to be the slowest.
1 Answer 1
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)
-
\$\begingroup\$ Thanks for your time Winston! Your advise is very useful. \$\endgroup\$chespinoza– chespinoza2013年01月16日 19:10:25 +00:00Commented Jan 16, 2013 at 19:10
Explore related questions
See similar questions with these tags.