我如何比较两个日期,看看哪个是后来,使用Python?

例如,我想检查当前日期是否超过了我正在创建的假期日期列表中的最后一个日期,这样它就会自动发送一封电子邮件,告诉管理员更新holiday.txt文件。


当前回答

计算两个日期的天数差,可以这样做:

import datetime
import math

issuedate = datetime(2019,5,9)   #calculate the issue datetime
current_date = datetime.datetime.now() #calculate the current datetime
diff_date = current_date - issuedate #//calculate the date difference with time also
amount = fine  #you want change

if diff_date.total_seconds() > 0.0:   #its matching your condition
    days = math.ceil(diff_date.total_seconds()/86400)  #calculate days (in 
    one day 86400 seconds)
    deductable_amount = round(amount,2)*days #calclulated fine for all days

因为如果比截止日期多一秒,我们就得收费

其他回答

其他使用datetime和比较的答案也只适用于时间,没有日期。

例如,要检查现在是早8点还是早8点,我们可以使用:

import datetime

eight_am = datetime.time( 8,0,0 ) # Time, without a date

并随后与:

datetime.datetime.now().time() > eight_am  

返回True

python是最简单的语言,在python中比较日期非常容易,python操作符<,>和==非常适合datetime对象。 每一个在python中都有自己的含义:

<表示日期早于第一个日期 >表示日期延后 ==表示日期与第一天相同 所以,对于你的情况:

import datetime

date = datetime.datetime(2000, 1, 1) # Replace with whatever you want
now = datetime.datetime.now() # You can even find the current date and time using this expression

if date < now:
    print('past')
elif date > now:
    print('future')
else:
    print('present')
# This would print "past"

使用datetime方法和操作符<及其同类。

>>> from datetime import datetime, timedelta
>>> past = datetime.now() - timedelta(days=1)
>>> present = datetime.now()
>>> past < present
True
>>> datetime(3000, 1, 1) < present
False
>>> present - datetime(2000, 4, 4)
datetime.timedelta(4242, 75703, 762105)

计算两个日期的天数差,可以这样做:

import datetime
import math

issuedate = datetime(2019,5,9)   #calculate the issue datetime
current_date = datetime.datetime.now() #calculate the current datetime
diff_date = current_date - issuedate #//calculate the date difference with time also
amount = fine  #you want change

if diff_date.total_seconds() > 0.0:   #its matching your condition
    days = math.ceil(diff_date.total_seconds()/86400)  #calculate days (in 
    one day 86400 seconds)
    deductable_amount = round(amount,2)*days #calclulated fine for all days

因为如果比截止日期多一秒,我们就得收费

datetime。Date (2011, 1,1) < datetime。date(2011, 1,2)返回True。

datetime。Date (2011, 1,1) - datetime。Date(2011, 1,2)将返回datetime.timedelta(-1)。

datetime。日期(2011,1,1)+日期时间。Date(2011, 1,2)将返回datetime.timedelta(1)。

去看医生。