datetime, compare 2 dates, can this be done a smarter way?

Asked by Alex Nilsson

I've checked http://docs.python.org/library/datetime.html, but can't seem to get two dates to compare to each other in a smart way.

What I need is to copy a date from an Excelsheet and compare it to todays date, to find out if a case is due or not.
What I have is this and that's hardly optimal:

import datetime

# This is the date/time i get from Excel and is just set here to get a working example:
duedate = "26-09-2012 00:00:00"

#Setting date, month and year to 3 strings
datoNow = str(datetime.datetime.now().strftime("%d"))
MDNow = str(datetime.datetime.now().strftime("%m"))
AarNow = str(datetime.datetime.now().strftime("%Y"))

if not duedate == "-":
    Temp1 = duedate.split(" ")
    Temp2 = Temp1[0].split("-")
    dato, MD, Aar = Temp2[0], Temp2[1], Temp2[2]

    if AarNow >= Aar and MDNow >= MD and datoNow > dato:
        print ("This is due")

Question information

Language:
English Edit question
Status:
Solved
For:
SikuliX Edit question
Assignee:
No assignee Edit question
Solved by:
RaiMan
Solved:
Last query:
Last reply:

This question was reopened

Revision history for this message
RaiMan (raimund-hocke) said :
#1

What about:

nowdate = time.strftime("%d-%m-%Y %H:%M:%S")

module time is already imported by Sikuli
strftime() takes now(), if no time given

so that is all
duedate = "26-09-2012 00:00:00"
if duedate < time.strftime("%d-%m-%Y %H:%M:%S"): print "in the past"

Revision history for this message
Alex Nilsson (benthien-nilsson) said :
#2

That'll do it, thx :-)

Revision history for this message
Alex Nilsson (benthien-nilsson) said :
#3

Thanks RaiMan, that solved my question.

Revision history for this message
Alex Nilsson (benthien-nilsson) said :
#4

Or so i thought, it doesn't play nice with years.. if you set the duedate = "26-09-2013 17:58:23"
and run:
duedate < time.strftime("%d-%m-%Y %H:%M:%S"): print "in the past"
It'll say it's in the past..

Revision history for this message
Best RaiMan (raimund-hocke) said :
#5

Uuups, since it is string compare, we have to have the sequence as Y-M-D.

d = "26-09-2013 17:58:23"
duedate = "%s-%s-%s%s"%(d[6:10], d[3:5], d[0:2], d[10:])
if duedate < time.strftime("%Y-%m-%d %H:%M:%S"): print "in the past"

Revision history for this message
Alex Nilsson (benthien-nilsson) said :
#6

Thanks RaiMan, that solved my question.