Skip to content

Remove the time challenge in Python

The challenge

You’re re-designing a blog and the blog’s posts have the following format for showing the date and time a post was made:

Weekday Month Daytime e.g., Friday May 2, 7pm

You’re running out of screen real estate, and on some pages you want to display a shorter format, Weekday Month Day that omits the time.

Write a function, shortenToDate, that takes the Website date/time in its original string format, and returns the shortened format.

Assume shortenToDate’s input will always be a string, e.g. “Friday May 2, 7pm”. Assume shortenToDate’s output will be the shortened string, e.g., “Friday May 2”.

Test cases

Test.describe("Basic tests") Test.assert_equals(shorten_to_date("Monday February 2, 8pm"), "Monday February 2") Test.assert_equals(shorten_to_date("Tuesday May 29, 8pm"), "Tuesday May 29") Test.assert_equals(shorten_to_date("Wed September 1, 3am"), "Wed September 1") Test.assert_equals(shorten_to_date("Friday May 2, 9am"), "Friday May 2") Test.assert_equals(shorten_to_date("Tuesday January 29, 10pm"), "Tuesday January 29")
Code language: Python (python)

The solution in Python

Option 1:

def shorten_to_date(long_date): # split by the `,` and return the first section return long_date.split(",")[]
Code language: Python (python)

Option 2:

def shorten_to_date(long_date): return long_date[:long_date.index(',')]
Code language: Python (python)

Option 3 (using splicing):

def shorten_to_date(long_date): # get the location of the `,` num = long_date.find(',') # return the splice return long_date[:num]
Code language: Python (python)

See also  How to Force Gitlab pipeline to fail on condition
Notify of
Inline Feedbacks
View all comments
Would love your thoughts, please comment.x