Python Django 字符串到日期格式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22918095/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 01:58:35  来源:igfitidea点击:

Django string to date format

pythondjangodatetime

提问by SAFEER N

I want to convert my string date to django date format. I tried a method. but did not work.

我想将我的字符串日期转换为 django 日期格式。我尝试了一个方法。但没有用。

date = datetime.datetime.strptime(request.POST.get('date'),"Y-mm-dd").date()

I got this error.

我收到了这个错误。

time data '2014-04-07' does not match format 'Y-mm-dd'

what 's wrong in my code.

我的代码有什么问题。

采纳答案by alecxe

It should be %Y-%m-%d:

它应该是%Y-%m-%d

>>> s = "2014-04-07"
>>> datetime.datetime.strptime(s, "%Y-%m-%d").date()
datetime.date(2014, 4, 7)

According to the documentation:

根据文档

  • %Ystands for a year with century as a decimal number
  • %m- month as a zero-padded decimal number
  • %d- day of the month as a zero-padded decimal number
  • %Y代表以世纪为十进制数的年份
  • %m- 月份作为零填充的十进制数
  • %d- 以零填充的十进制数表示的月份日期

Hope that helps.

希望有帮助。

回答by Daniel Backman

It might be convenient to use django's dateparsein this case.

在这种情况下使用 django 的dateparse可能会很方便。

from django.utils.dateparse import parse_date
date_str = request.POST.get('date')
date = parse_date(date_str)

回答by Mesut Tasci

django.utils.dateparse.parse_datefunction will return Noneif given date not in %Y-%m-%dformat

django.utils.dateparse.parse_dateNone如果给定的日期%Y-%m-%d格式不正确,函数将返回

I have not found a function in django source code to parse string by DATE_INPUT_FORMATS. So I wrote a custom helper function for that and I have added to here for help others.

我还没有在 django 源代码中找到一个函数来解析字符串DATE_INPUT_FORMATS。因此,我为此编写了一个自定义帮助器函数,并将其添加到此处以帮助其他人。

from datetime import datetime
from django.utils.formats import get_format

def parse_date(date_str):
    """Parse date from string by DATE_INPUT_FORMATS of current language"""
    for item in get_format('DATE_INPUT_FORMATS'):
        try:
            return datetime.strptime(date_str, item).date()
        except (ValueError, TypeError):
            continue

    return None