Getting a valid datetime format from a string 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.
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)