Python Django - 仅从 datetime.strptime 获取日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18039680/
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 09:47:17  来源:igfitidea点击:

Django - Get only date from datetime.strptime

pythondjangodatetime

提问by Nikhilesh

I have start date field in database as date (not datetime). In my save method in forms.py I'm using datetime.strptime(date_string, '%Y-%m-%d')to convert string to date. The method returns me formatted date along with time, i.e, "2006-08-03 00:00:00".

我将数据库中的开始日期字段作为日期(不是日期时间)。在我在 forms.py 中的保存方法中,我使用datetime.strptime(date_string, '%Y-%m-%d')将字符串转换为日期。该方法返回格式化日期和时间,即“2006-08-03 00:00:00”。

I want just the date and no time. Because I get an "invalid date format error" saying "It must be in YYYY-MM-DD format", I'm stuck on this and frustrated. Can anyone help me out with this?

我只想要日期而不是时间。因为我收到一个“无效的日期格式错误”,说“它必须是 YYYY-MM-DD 格式”,我被困在这个问题上并感到沮丧。谁能帮我解决这个问题?

采纳答案by lazy functor

I think you need date object not datetime. Try converting datetime to date using date() method on datetime object

我认为您需要日期对象而不是日期时间。尝试使用 datetime 对象上的 date() 方法将日期时间转换为日期

from datetime import datetime
datetime.strptime('2014-12-04', '%Y-%m-%d').date()