我有以下条目:
2013-01-09 06:13:51,464 DEBUG module 159 Djang...
从此字符串中提取日期的最短(最佳)方式是什么?
答案 0 :(得分:4)
你需要保持微秒吗?
>>> 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)
答案 1 :(得分:1)
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')
答案 2 :(得分:0)
>>> 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)