【问题标题】:Creating function just to return date创建函数只是为了返回日期
【发布时间】:2020-04-04 20:58:50
【问题描述】:

该函数应将字符串列表作为输入。输入列表中的每个字符串都被格式化为 'yyyy-mm-dd hh:mm:ss'。 该函数应返回一个字符串列表,其中返回列表中的每个元素仅包含 'yyyy-mm-dd' 格式的日期。

def date_parser(dates):
    """

    This function takes as input a list of these datetime strings and returns only the date in 'yyyy-mm-dd' format.

    Parameters:
    -----------
    items: (list), list of datetime strings.

    Returns:
    --------
    returns a list of strings where each element in the returned list contains only the date in the 'yyyy-mm-dd' format.

    """
    my_list = []

    for date in dates:
        my_list.append(date)

        my_list[:10]

    return my_list

### START FUNCTION
def date_parser(dates):
    """

    This function takes as input a list of these datetime strings and returns only the date in 'yyyy-mm-dd' format.

    Parameters:
    -----------
    items: (list), list of datetime strings.

    Returns:
    --------
    returns a list of strings where each element in the returned list contains only the date in the 'yyyy-mm-dd' format.

    """
    my_list = []

    for date in dates:
        my_list.append(date)

        my_list[:10]

    return my_list

【问题讨论】:

  • 您面临的问题是什么?
  • 我需要编写一个只返回日期而不是日期时间的函数。给出的值是'2019-11-29 12:50:54'、'2019-11-29 12:46:53'、'2019-11-29 12:46:10'

标签: python python-3.x list date datetime


【解决方案1】:

如果您可以确保输入列表仅包含有效日期,您可以简单地执行以下操作:

my_list = []

    for date in dates:
        my_list.append(date[:10])
    return my_list

或者使用list comprehension(我觉得更好看)

return [datetime_string[:10] for datetime_string in dates]

【讨论】:

    猜你喜欢
    • 2021-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-12
    • 2021-04-22
    • 1970-01-01
    • 1970-01-01
    • 2020-06-26
    相关资源
    最近更新 更多