Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Number Trouble with Regex in Python

Tags:

python

regex

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.

like image 591
Shahab Avatar asked Feb 12 '26 15:02

Shahab


2 Answers

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.

like image 147
JMax Avatar answered Feb 15 '26 06:02

JMax


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

like image 31
Marcin Avatar answered Feb 15 '26 06:02

Marcin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!