开发者

convert string of millisecond into datetime in python

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 fo开发者_运维知识库rmat. 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


>>> 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'


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'
>>>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜