Skip to content

Instantly share code, notes, and snippets.

@ian-weisser
Created April 5, 2014 19:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ian-weisser/9997196 to your computer and use it in GitHub Desktop.
Save ian-weisser/9997196 to your computer and use it in GitHub Desktop.
Test a GTFS file's calendar and calendar_dates tables for a specific date (like today)
#!/usr/bin/python3
"""
Check a GTFS file's calendar and calendar_dates tables.
Return True if the dates are current or future.
Return False if all dates are in the past and the GTFS file
can be safely deleted.
This is a working example. Try it. Edit the path to match your GTFS file.
"""
import zipfile
def valid_dates(gtfs_path_and_file, date_string):
"""
Check a GTFS file's calendar and calendar_dates tables.
If all valid dates are in the past, return False.
If any valid dates include the date string or the future, return True.
Date string is format YYYYMMDD, just like GTFS dates.
"""
gtfs_zipfile = zipfile.ZipFile(gtfs_path_and_file, mode='r')
valid = False
if 'calendar.txt' in gtfs_zipfile.namelist():
cal_string = gtfs_zipfile.read('calendar.txt').decode('utf-8')
cal_lines = cal_string.split('\r\n')
del cal_lines[0] # Delete the header row
for line in cal_lines:
if len(line.split(',')) < 9:
continue
start_date = int(line.split(',')[8])
end_date = int(line.split(',')[9])
if start_date >= int(date_string) \
or end_date >= int(date_string):
valid = True
break
elif 'calendar_dates.txt' in gtfs_zipfile.namelist():
cal_string = gtfs_zipfile.read('calendar_dates.txt').decode('utf-8')
cal_lines = cal_string.split('\r\n')
del cal_lines[0] # Delete the header row
for line in cal_lines:
if len(line.split(',')) < 3:
continue
date = line.split(',')[1]
if date >= date_string:
valid = True
break
gtfs_zipfile.close()
return valid
if __name__ == "__main__":
GTFS_FILE = '/var/cache/gtfs/Milwaukee County Transit System/20140401.gtfs'
TODAY = '20140331'
print(valid_dates(GTFS_FILE, TODAY))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment