Python – How to replace just time numbers from date?

Question:

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!

Asked By: Troy9090

||

Answers:

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

I’m relatively inexperienced posting to this platform but I hope I can help.When I tried to run your code it gave an "EOL while scanning string literal" syntax error at the 2nd to last line. It looks like you only need an additional single quote to correct (I don’t know the full intention of what was needed there).

I see that another comment provided an answer for handling this as date/time but if the format will always be string, you may also like the below approach:

import re #Module needed

test_string = "September 16, 2022, 11:31 am 20 Days" #Example string

def string_format(string):
    splt_char = "," #Character being used as split point

    splt_parts = string.split(splt_char) #New variable to hold the split items

    res = splt_char.join(splt_parts[:2]) #joining the split items before the 2nd split point.

    day = re.findall("d+",string)[-1] #Get the day # by finding all numbers in original string and saving the last.

    razzle_dazzle = "s" if int(day) > 1 else "" #Treats the day variable as an interger and simply equals "s" if more than 1.

    desired_output = f"{res} ({day} Day{razzle_dazzle})" #final variable putting it all together.

    return(desired_output) 
print(string_format(test_string))

This gives me the output of:

September 16, 2022 (20 Days)
Answered By: Omnishroom
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.