如何从日期格式中删除时间?

2024-04-26 10:20:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我在处理代码战中的卡塔时遇到了麻烦。kata的目标是从日期格式中删除时间(我将在下面列出说明)。我使用的方法是索引拼接,删除逗号后的所有内容(这是时间所在的位置)。我正在用Python版本3.8编写此代码

Instructions

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 Day, time 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".

代码:

def shorten_to_date(long_date):
    #your code here
    new_date = long_date[:-5]
    
    print(new_date)

Tags: andthe代码reyouformatdatestring
2条回答

我使问题变得比看起来更难,主要问题之一是我一直调用print而不是返回函数。另一个错误是我想使用index而不是仅仅使用rsplit()删除逗号后面的所有内容

def shorten_to_date(long_date):
    #This line of code will remove all text after the comma is added
    return long_date.rsplit(',')[0]

并非所有的字符串都有相同的长度,因此最好只使用逗号分隔并返回第一个字符串

new_date = long_date.split(',')[0]

如果您确实需要使用索引,您可以在每个字符串中找到逗号的索引,并使用它对其进行切片

def shorten_to_date(long_date):
    index = long_date.index(',')
    return long_date[:index]

相关问题 更多 >