Issue
I am a beginner in python, and need some help from Pro!
I just want to delete only the time that appears on date output and not the date itself.
print(trh)
Output:
September 16, 2022, 11:31 pm 20 Days
.
I tried several ways with .replace()
but I didn't get what I want.
print(trh).replace('TimeString','')
For Example:
I just want to delete only , 11:31 pm
in output with .replace()
To show on output like this:
September 16, 2022 (20 Days)
.
Code:
def month_string_to_number(ay):
m = {
'jan': 1,
'feb': 2,
'mar': 3,
'apr':4,
'may':5,
'jun':6,
'jul':7,
'aug':8,
'sep':9,
'oct':10,
'nov':11,
'dec':12
}
s = ay.strip()[:3].lower()
try:
out = m[s]
return out
except:
raise ValueError('Not a month')
import time
from datetime import date
def tarih_clear(trh):
ay=""
gun=""
yil=""
trai=""
my_date=""
sontrh=""
out=""
ay=str(trh.split(' ')[0])
gun=str(trh.split(', ')[0].split(' ')[1])
yil=str(trh.split(', ')[1])
ay=str(month_string_to_number(ay))
trai=str(gun)+'/'+str(ay)+'/'+str(yil)
my_date = str(trai)
if 1==1:
d = date(int(yil), int(ay), int(gun))
sontrh = time.mktime(d.timetuple())
out=(int((sontrh-time.time())/86400))
return out
second Code
if not data.count('phone')==0:
hcr="\33[1;36m"
hcc=hcc+1
trh=""
if 'end_date' in data:
trh=data.split('end_date":"')[1]
trh=trh.split('"')[0]
else:
try:
trh=data.split('phone":"')[1]
trh=trh.split('"')[0]
if trh.lower()[:2] =='un':
DaysRemain=(" Days")
else:
DaysRemain=(str(tarih_clear(trh))+" Days")
trh=trh+' '+DaysRemain
except:pass
Thanks!
Solution
I would suggest you not to write all these logic for parsing and understanding the dates, if it is a standard format always - like the example you shared.
You can use the python's capability to parse and understand dates, also use regex to make string searches.
An example approach to reset the date-contained-string is below
import re
from datetime import datetime
def get_formatted_time(date_str):
d_pattern = r"(\d+ Days)"
parts = re.split(d_pattern, date_str) #Split the string based on the pattern of days
date_string = parts[0] #The date time string part
days_string = parts[1] #the days count
date = datetime.strptime(date_string.strip(), "%B %d, %Y, %I:%M %p") #Parse to a valid date time object
removed_time_str = date.strftime("%B %d, %Y") #format as per your need
return f"{removed_time_str} ({days_string})" #concat and build your final representation.
print(get_formatted_time("September 16, 2022, 11:31 am 20 Days"))
This gives you
September 16, 2022 (20 Days)
Answered By - Kris
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.