views:

204

answers:

2

I am a newbie in Python. I want to subtract interval time from my log file, but the problem is I cannot convert millisecond string of log file into datetime format. For example, I have 15:55:05.12345 and I want to remove 5.12345 seconds from this string, and show result of 15.55.00.00000 in Python. How can I do that? Currently, I am using python 2.5.

Thank you in advance.

Sorry, I meant I want to subtract value for example, remove 00:00:05.1000 so, i should get 15:55:00:02345

+1  A: 
>>> import datetime
>>> s = '15:55:05.12345'
>>> datetime.datetime.strptime(s.rpartition('.')[0], '%H:%M:%S').strftime('%H.%M.00.00000')
'15.55.00.00000'

edit after clarification:
there is no way to do this with Python standard library, only working directly with strings:

>>> s[:6]+ '00' + s[-6:]
'15:55:00.12345'
SilentGhost
Sorry I mean I want to substact value for example, remove 00:00:05.1000 so, i should get 15:55:00:02345
newbie
I have to deal with the huge log files. I cannot go for setting all values of strings manually. Do you have any other suggestion that I can do to solve this?
newbie
@newbie: I don't understand your objection? who says that you should do it manually?
SilentGhost
Sorry for my misunderstanding. Now I can solve it. Thank you very much!
newbie
@newbie: you're welcome to accept my answer if it solves your problem.
SilentGhost
A: 

I see that you need to subtract from the value, so I would use timedelta objects because you can do math with those.

>>> value = '15:55:05.123450'
>>> m = re.match('(\d+):(\d+):(\d+\.\d+)', value)
>>> hour = int(m.group(1))
>>> min = int(m.group(2))
>>> sec = float(m.group(3))
>>> now = datetime.timedelta(hours=hour,minutes=min,seconds=sec)
>>> str(now)
'15:55:05.123450'
>>>
>>> delta = datetime.timedelta(seconds=5.1)
>>>
>>> earlier = (now - delta)
>>> str(earlier)
'15:55:00.023450'
>>>
joefis