I have a string
string = "Friday07:48 AM"
How do I get rid of "Friday"? I could simply use a replace() function but this string could also be any other day of the week. So it could look like:
string = "Sunday07:48 AM"
How do I only get "07:48 AM"?
We can utilize the fact that every day of the week in English ends in the substring 'day' to locate that within your string, and then go from three indices farther from where 'day' starts until the end of your string.
date_str = "Friday07:48 AM"
new_str = date_str[date_str.index('day')+3:]
new_str # '07:48 AM'
As an aside, never name a string 'string' or 'str', because those are special words in Python.
Well for everything except Saturday and Wednesday you could just grab it by:
day = string[0:6]
but in the all cases IF the time stamp in the front always holds the same index you could:
day = string[:-8]
Try it in the shell
How about using regular expressions?
import re
re.search("([a-z]+)(.*)",string,flags=re.I).group(2)
Related
My file name looks like as follow:
show_data_paris_12112019.xlsx
I want to extract the date only and I have tried this script:
date = os.path.basename(xls)
pattern = r'(?<=_)_*(?=\.xlsx)'
re.search(pattern, date).group(0)
event_date = re.search(pattern, date).group(0)
event_date_obj = datetime.strptime (event_date, '%Y%m%d')
but It gives me errors. How can I fix this?
Thank you.
It looks to me like the regex you're using is also at fault, and so it fails when trying to group(0) from the empty return.
Assuming all your dates are stored as digits the following regex i've made seems to work quite well.
(?!.+_)\d+(?=\.xlsx)
The next issue is when formatting the date it experiences an issue with the way you're formatting the date, to me it looks like 12112019 would be the 12/11/2019 obviously this could also be the 11/12/2019 but the basic is that we change the way strftime formats the date.
So for the date / month / year format we would use
# %d%m%Y
event_date_obj = datetime.strptime(event_date, '%d%m%Y')
And we would simply swap %d and %m for the month / date / year format. So your complete code would look something like this:
date = os.path.basename(xls)
pattern = "(?!.+_)\d+(?=\.xlsx)"
event_date = re.search(pattern, date).group(0)
event_date_obj = datetime.strptime (event_date, '%d%m%Y')
For further information on how to use strftime see https://strftime.org/.
_* matches a sequence of zero or more underscore characters.
(?<=_) means that it has to be preceded by an underscore.
(?=\.xlsx) means that it has to be followed by .xlsx.
So this will match the ___ in foo____.xlsx. But it doesn't match your filename, because the data is between the underscore and .xlsx.
You should match \d+ rather than _* between the lookbehind and lookahead.
pattern = r'(?<=_)\d+(?=\.xlsx)'
And if the data is always 8 digits, use \d{8} to be more specific.
In strftime %b is the month name
>>> '{:%b}'.format(datetime.now())
'Apr'
I can uppercase it using chinese-hat modifier carrot thing
>>> '{:%^b}'.format(datetime.now())
'APR'
How do I lowercase it? i.e. to get the result '{:%b}'.format(dt).lower(), but using the template rather than a post-processing step.
Just add .lower() after datetime.now(). As far as I know there is no other way to do it.
i am trying to do string manipulation based on format. str.replace(old,new) alllows changing by specific string pattern. is it possible to find and replace by format? for example,
i want to find all datetime like value in a long string and replace it with another format
assuming % is wildcard for number and datetime is %%/%%/%%T%%:%%
str.replace(%%/%%/%%T%%:%%, 'dummy value')
EDIT:
sorry i should have been more clearer. re.sub seems like I can use that, but how do it substitute it with a date converted value. in this case, e.g.
YY/MM/DDTHH:MM to (YY/MM/DD HH:MM)+8 hours
The easiest way to do this is probably using a combination of regular expression syntax, applying re.sub and using the fact that the repl parameter can be a function that takes a match and returns a string to replace it, and datetime's syntax for strptime and strftime:
>>> from datetime import datetime
>>> import re
>>> def replacer(match):
return datetime.strptime(
match.group(), # matched text
'%y/%m/%dT%H:%M', # source format in datetime syntax
).strftime('%d %B %Y at %H.%M') # destination format in datetime syntax
>>> re.sub(
r'\d{2}/\d{2}/\d{2}T\d{2}:\d{2}', # source format in regex syntax
replacer, # function to process match
'The date and time was 12/12/12T12:12 exactly.', # string to process
)
'The date and time was 12 December 2012 at 12.12 exactly.'
The only downside of this is that you need to define the source format in both datetime and re syntax, which isn't very DRY; if they don't match, you'll get nowhere.
st = """
What kind of speCialist would we see for this?He also seems to have reactions to the red dye cochineal/carmine cialist,I like Cialist much
"""
here I need to replace only the Cialist string(exact match) also it may has comma at the end
The word "spe*cialist*" should not be thrown
i tried with this regex.
bold_string = "<b>"+"Cialist"+"</b>"
insensitive_string = re.compile(re.escape("cialist"), re.IGNORECASE)
comment = insensitive_string.sub(bold_string,st)
but it throws the string specialist also.
Could you suggest me to fix this?
One more issue with replacing the hexadecimal character in python.
date_str = "28-06-2010\xc3\x82\xc2\xa008:48 PM"
date_str = date_str.replace("\n","").replace("\t","").replace("\r","").replace("\xc3\x82\xc2\xa"," ")
date_obj = datetime.strptime(date_str,"%d-%m-%Y %H:%M %p")
Error: time data '08-09-2005\xc3\x82\xc2\xa010:18 PM' does not match format '%d-%m-%Y %H:%M %p'
Here I am not able to replace the hex characters with space for matching with datetime pattern .
Could you please help out of this issue?
For your second Q:
>>> re.sub(r'\\[a-zA-z0-9]{2}', lambda L: str(int(L.group()[2:], 16)), text)
'28-06-20101238212210008:48 PM'
That either re-organise that for your strptime, or have strptime interpret that.
Two questions in one?
replace your regex with a word boundary so it's re.sub(r'\bcialist\b', '', your_string, re.I)
Use \b to match a word boundary. Then it becomes simples :)
import re
st = """
What kind of speCialist would we see for this?He also seems to have reactions to the red dye cochineal/carmine cialist,I like Cialist much
"""
print re.sub(r'\bCialist\b', "<b>Cialist</b>", st)
For the second question you're missing a 0 at the end of your last replace string. Just add 0 and it works :)
date_str = "28-06-2010\xc3\x82\xc2\xa008:48 PM"
print date_str
date_str = date_str.replace("\n","").replace("\t","").replace("\r","").replace("\xc3\x82\xc2\xa0"," ")
print repr(date_str)
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.
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.
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
I think you're confusing the circumflex for start of line and dollar for end of line. Try ^[\d-]+.
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
>>> date = '"2011-10-01 19:25:01"'
>>> date.strip('"').split()[0]
'2011-10-01'
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.