5

To get date I use this block:

currentDate = date.today()
today = currentDate.strftime('%m/%d/%Y')

It returns me this format 12/22/2014 or 01/02/2015 Then I have to compare to string from the file (note: I can't change the string) 12/22/2014 or 1/2/2015 and I use:

if l[0] == today:

In second case it obviously failed. My question: how could I change strftime() in order to return only one charachter for month and day when it has preceeding zero?

1
  • 3
    compare two datetime objects not strings Commented Jan 3, 2015 at 18:07

3 Answers 3

3

Referring to the documentation, it doesn't appear that there is a character sequence for this. However, you could correct the result as follows:

today = currentDate.strftime('%m/%d/%Y').replace("/0", "/")
if today[0] == '0':
    today = today[1:]

This will eliminate any leading 0s so long as the values are split with a forward slash.

Sign up to request clarification or add additional context in comments.

5 Comments

That would not replace the first leading 0
-OMGthchy, I like you suggestion, I did this: (Pdb) today = currentDate.strftime('%m/%d/%Y').replace("/0", "/") (Pdb) p today '01/3/2015' Hence it replaced second zero, is it option to remove both zeros?
@susik there was a typo where I checked it against 0 not '0', this should work now
Great!! Works perfect now both when date has or does not have zero in date. Appreciate it.
@susik no problem. Now if you don't understand the code I advise you read through it until you do, as things like this come up a lot.
2

just compare datetime objects:

from datetime import datetime, date

currentDate = date.today()
file_dt = "1/3/2015"
dt2 = datetime.strptime(file_dt,"%m/%d/%Y")
print(dt2.date() == currentDate)

Comments

0
today = currentDate.strftime('%-m/%-d/%Y')

WARNING, not standard, so could not work on some platforms (check strftime(3) documentation, section "Glibc notes"). Anyway, I agree with other answers, better to compare datetime objects

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.