Shahab
Shahab

Reputation: 2067

Number Trouble with Regex in Python

I'm trying to filter a date retrieved from a .csv file, but no combination I try seems to work. The date comes in as "2011-10-01 19:25:01" or "year-month-date hour:min:sec".

I want just the year, month and date but I get can't seem to get ride of the time from the string:

date = bug[2] # Column in which the date is located  
date = date.replace('\"','') #getting rid of the quotations  
mdate = date.replace(':','')  
re.split('$[\d]+',mdate) # trying to get rid of the trailing set of number (from the time)

Thanks in advance for the advice.

Upvotes: 2

Views: 126

Answers (6)

JMax
JMax

Reputation: 26611

If your source is a string, you'd probably better use strptime

import datetime
string = "2011-10-01 19:25:01"
dt = datetime.datetime.strptime(string, "%Y-%m-%d %H:%M:%S")

After that, use

dt.year
dt.month
dt.day

to access the data you want.

Upvotes: 8

murgatroid99
murgatroid99

Reputation: 20297

One problem with your code is that in your last regular expression, $ matches the end of the string, so that regular expression will never match anything. You could do this much more simply by splitting by spaces and only taking the first result. After removing the quotation marks, the line

date.split()

will return ["2011-10-01", "19:25:01"], so the first element of that list is what you need.

Upvotes: 1

kev
kev

Reputation: 161964

>>> date = '"2011-10-01 19:25:01"'
>>> date.strip('"').split()[0]
'2011-10-01'

Upvotes: 1

TyrantWave
TyrantWave

Reputation: 4673

If the format is always "YYYY-MM-DD HH:mm:ss", then try this:

date = date[1:11]

In a prompt:

>>> date = '"2012-01-12 15:13:20"'
>>> date[1:11]
'2012-01-12'
>>> 

No need for regex

Upvotes: 1

bkzland
bkzland

Reputation: 569

I think you're confusing the circumflex for start of line and dollar for end of line. Try ^[\d-]+.

Upvotes: 1

Marcin
Marcin

Reputation: 49886

Use datetime to parse your input as a datetime object, then output it in whatever format you like: http://docs.python.org/library/datetime.html

Upvotes: 6

Related Questions