可能重复:
将字符串转换为日期时间
我得到了如下日志条目:
2013-01-09 06:13:51,464 DEBUG module 159 Djang...
从这个字符串中提取日期的最短(最好)方法是什么?
可能重复:
将字符串转换为日期时间
我得到了如下日志条目:
2013-01-09 06:13:51,464 DEBUG module 159 Djang...
从这个字符串中提取日期的最短(最好)方法是什么?
你需要保持微秒吗?
>>> import re
>>> log = "2013-01-09 06:13:51,464 DEBUG module"
>>> p = re.compile("\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2},\d*")
>>> time_str = p.findall(log)[0]
>>> time_str
'2013-01-09 06:13:51,464'
>>> from datetime import datetime
>>> date_time = datetime.strptime(time_str, '%Y-%m-%d %H:%M:%S,%f')
>>> date_time
datetime.datetime(2013, 1, 9, 6, 13, 51, 464000)
from datetime import datetime
val = '2013-01-09 06:13:51,464'.split(',')[0] # Remove milliseconds
date_object = datetime.strptime(val, '%Y-%m-%d %H:%M:%S')
>>> a = "2013-01-09 06:13:51,464 DEBUG module"
>>> a = a.split(" ")
>>> date,time = a[0], a[1]
>>> date = date.split("-")
>>> time = time.split(",")[0].split(":")
>>> date
['2013', '01', '09']
>>> time
['06', '13', '51']
>>> args_list = [int(i) for i in date]
>>> args_list.extend( [int(i) for i in time])
>>> args_list
[2013, 1, 9, 6, 13, 51]
>>> import datetime
>>> datetime.datetime(*args_list)
datetime.datetime(2013, 1, 9, 6, 13, 51)