在没有时间的情况下在python中创建日期

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

create date in python without time

pythonpython-2.7python-3.x

提问by ruby student

I need to get the current date without time and then compare that date with other entered by user

我需要获取没有时间的当前日期,然后将该日期与用户输入的其他日期进行比较

import datetime
now = datetime.datetime.now()

Example

例子

currentDate="01/08/2015"
userDate="01/07/2015"
if currentData > userDate:
 .........
else:
  ...................

采纳答案by Anand S Kumar

You can use datetime.dateobjects , they do not have a time part.

您可以使用datetime.date对象,它们没有时间部分。

You can get current date using datetime.date.today(), Example -

您可以使用datetime.date.today(),例如 -

now = datetime.date.today()

This would give you an object of type - datetime.date. And you can get the date()part of a datetimeobject , by using the .date()method , and then you can compare both dates.

这会给你一个类型 - 的对象datetime.date。您可以通过使用方法获取对象的date()一部分,然后您可以比较两个日期。datetime.date()

Example -

例子 -

now = datetime.date.today()
currentDate = datetime.datetime.strptime('01/08/2015','%d/%m/%Y').date()

Then you can compare them.

然后你可以比较它们。

Also, to convert the string to a date , you should use dateimte.strptime()as I have used above , example -

此外,要将字符串转换为日期,您应该dateimte.strptime()像我上面使用的那样使用,例如 -

currentDate = datetime.datetime.strptime('01/08/2015','%d/%m/%Y').date()

This would cause, currentDateto be a datetime.dateobject.

这将导致,currentDate成为一个datetime.date对象。



Example/Demo -

示例/演示 -

>>> now = datetime.date.today()
>>> currentDate = datetime.datetime.strptime('01/08/2015','%d/%m/%Y').date()
>>> now > currentDate
False
>>> now < currentDate
False
>>> now == currentDate
True

回答by TigerhawkT3

If you want to compare dates, then compare dates, not strings. Use datetime.datetime.strptime()to parse the user's entered date.

如果要比较日期,请比较日期,而不是字符串。使用datetime.datetime.strptime()解析用户输入的日期。

import datetime
now = datetime.datetime.now()
userDate = "01/07/2015"
if datetime.datetime.strptime(userDate, '%m/%d/%Y') < now:
    ...