I am learning Python 3
I have several pieces of code that compares dates.
The problem is I don't understand how to read a date from a text file and then use it in my code so I can compare it with todays date.
I get errors like - int is not in date format - or the date is read as
1-1-1900

Recommended Answers

All 3 Replies

Here is the code that I am having trouble with. I want to read in a date from a text file and compare it to todays date. The date is in this format 2010-4-4.

from datetime import datetime, date
today = date.today()
print(today)
result_f = open("date.txt")
for line in result_f:
    result_f.close
print(line)
if line <= today:
    print('Oh wow')

I did not understand you loop. I did insert my string date routine here in your code I changed as little as posible to do something with it. Comments are my effort to understand the code

from datetime import datetime, date
today = date.today()
print(today)
result_f = open("date.txt")
for line in result_f: # read files lines to line one by one
    result_f.close ##  do nothing, result the address of close function

print(line) ## the value of for loop variable is unsure after loop

## normally line is last line in the file


datestring=line.rstrip() ## lets take out white space in the end

## this would make a year first date from the date as string yy-mm-dd in datestring
sep=[s for s in datestring if not s.isdigit()]

if len(sep)!=2 or sep[0] != sep [1]: print "Mixup separators",sep
else:
    datesep=sep[0]
    yy,mm,dd = (int(part) for part in datestring.split(datesep))

print( '-'*40)
print(datestring)
## your part changed to use the found date
if date(yy,mm,dd) <= today: ## line's day is today or in the past
    print('Oh wow')

## Show that file is open
print ("File is closed:",result_f.closed)
>>> a=open('/Tony/Tests/date.txt')
>>> a.close
<built-in method close of file object at 0x00E54610>
>>>
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.