18

I have a program that runs a Windows "net user" command to get the expiration date of a user. For example: "net user justinb /domain"

The program grabs the expiration date. I am taking that expiration date and setting it as variable datd

In the example below, we'll pretend the expiration date given was 1/10/2018. (Note: Windows does not put a 0 in front of the month)

import time

datd = "1/10/2018"

# places a 0 in front of the month if only 1 digit received for month
d = datd.split("/")
if len(d[0])==1:
    datd="0"+datd
    print("Changed to: " + datd)

myDate = (time.strftime("%m/%d/%Y"))

print ("This is today's date: " + myDate)

if datd <= myDate:    # if datd is is earlier than todays date
    print (" Password expired. ")
else:
    print (" Password not expired. ")

input(" Press Enter to exit.")

Right now, it gives me correct information if datd equals a date in 2017. I am getting a problem with the year 2018 and on though. It is telling me that 1/10/2018 comes before today's date of 10/24/2017. Is there a way I change the format of the dates properly so that they are read correctly in this program?

I want the output to say that the "Password is not expired" if datd = 1/10/2018

Adam Jaamour
  • 1,326
  • 1
  • 15
  • 31
Kade Williams
  • 1,041
  • 2
  • 13
  • 28
  • 1
    Use `datetime` module https://stackoverflow.com/questions/8142364/how-to-compare-two-dates – yash Oct 24 '17 at 16:29

1 Answers1

28
from datetime import datetime

string_input_with_date = "25/10/2017"
past = datetime.strptime(string_input_with_date, "%d/%m/%Y")
present = datetime.now()
past.date() < present.date()

This should do the job for you! Both handling day in format with leading 0 and without it.

Use .date() to make comparision of datetimes just to extent of daily date.

Warning: if you would like to be 100% correct and purist take care about timezone related issues. Make sure what time zone is assumed in your windows domain etc.

Reference:

datetime strptime - https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior

andilabs
  • 22,159
  • 14
  • 114
  • 151