1

Possible Duplicate:
Converting string into datetime

I got log entries like:

2013-01-09 06:13:51,464 DEBUG module 159 Djang...

What is the shortest (best) way to extract the date from this string?

Community
  • 1
  • 1
Jesvin Jose
  • 22,498
  • 32
  • 109
  • 202
  • You asked a question, answered it moments after asking, and then voted to close it? Sounds like you're just farming reputation with duplicate questions/answers. – Zoran Pavlovic Jan 09 '13 at 08:26
  • @ZoranPavlovic, I used the "answer your own question, QnA style"; and definitely not for rep farming – Jesvin Jose Jan 09 '13 at 10:24

3 Answers3

4

Do you need to keep the microsecond?

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

jinghli
  • 617
  • 4
  • 11
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')
Zoran Pavlovic
  • 1,166
  • 2
  • 23
  • 38
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)
Jesvin Jose
  • 22,498
  • 32
  • 109
  • 202
  • You're re-implementing the string parsing there which is already handled by the strptime function in the datetime class. Your answer is 4 times longer than mine. Also, why are you responding to your own question moments after asking it? – Zoran Pavlovic Jan 09 '13 at 08:24