1

I need to parse strings like "28-05-2014_02:44:32.630" from the Pandas lib.

The following code works like a charm with standard ISO date "28-05-2014T02:44:32.630":

In [1]: import dateutil.parser

In [3]: dateutil.parser.parse("28-05-2014T02:44:32.630", dayfirst=True)
Out[3]: datetime.datetime(2014, 5, 28, 2, 44, 32, 630000)

But not with my input string:

In [4]: dateutil.parser.parse("28-05-2014_02:44:32.630", dayfirst=True)
...
ValueError: unknown string format

How can i define my own parser ?

Thk in advance !


(edit)

Here is my working code (thanks to roippi):

import pandas
from datetime import datetime

def my_date_parser(d):
    return datetime.strptime(d, '%d-%m-%Y_%H:%M:%S.%f')

i = pandas.read_csv('test.tsv', sep='\t', index_col=0, parse_dates=True, date_parser=my_date_parser)
...

3 Answers 3

3

Use datetime.strptime directly:

parseme = "28-05-2014_02:44:32.630"

from datetime import datetime

datetime.strptime(parseme, '%d-%m-%Y_%H:%M:%S.%f')
Out[34]: datetime.datetime(2014, 5, 28, 2, 44, 32, 630000)
Sign up to request clarification or add additional context in comments.

Comments

2

Check out strptime https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior

The method definition is datetime.strptime(date_string, format)

So we could use datetime.strptime('28-05-2014_02:44:32.630', '%d-%m-%Y_%H:%M:%d.f')

Not sure about the microsecond, you may been to strip that. You could use '28-05-2014_02:44:32.630'.split('.')[0] to remove it.

Comments

0

you can use regex for crate your parser !

import re
def my_parser(string):
 return re.split(r':|-|_',string)

Demo:

>>> s="28-05-2014_02:44:32.630"
>>> import re
>>> s="28-05-2014_02:44:32.630"
>>> re.split(r':|-|_',s)
['28', '05', '2014', '02', '44', '32.630']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.