Skip to content

Instantly share code, notes, and snippets.

@satoshi7
Created May 13, 2015 10:49
Show Gist options
  • Save satoshi7/83b5ffe3304e8726b6ad to your computer and use it in GitHub Desktop.
Save satoshi7/83b5ffe3304e8726b6ad to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
import sys
import os
import errno
from datetime import datetime, date, timedelta
import urllib2
import yaml
import cPickle as pickle
argvs = sys.argv
argc = len(argvs)
datadir = "~/.jpholidayp"
cachefile = "cache"
cachedays = 5
class Cache:
def __init__(self):
try:
os.mkdir(os.path.expanduser(datadir))
except OSError:
if sys.exc_info()[1].errno != errno.EEXIST:
raise
def get(self):
file = os.path.join(os.path.expanduser(datadir), cachefile)
if not os.path.exists(file):
return None
today = date.today()
with open(file) as f:
dat = pickle.load(f)
if dat["expires"] <= today:
return None
else:
return dat["val"]
def set(self, val):
expires = date.today() + timedelta(cachedays)
dat = {"expires": expires, "val": val}
file = os.path.join(os.path.expanduser(datadir), cachefile)
with open(file, "w") as f:
pickle.dump(dat, f)
class HolidayJp:
URL = 'https://raw.githubusercontent.com/k1LoW/holiday_jp/master/holidays.yml'
def __init__(self):
cache = Cache()
c = cache.get()
if c:
dat = c["holiday_jp"]
else:
res = urllib2.urlopen(self.URL)
dat = yaml.load(res)
cache.set({"holiday_jp": dat})
self.holiday_jp = dat
def is_holiday(self, dt):
return dt in self.holiday_jp.keys()
class JpHoliday:
@classmethod
def is_national_holiday(self, dt):
holiday_jp = HolidayJp()
return holiday_jp.is_holiday(dt)
# value of datetime.weekday()
SATURDAY = 5
SUNDAY = 6
@classmethod
def is_holiday(self, dt):
w = dt.weekday()
if w == self.SATURDAY or w == self.SUNDAY:
return True
elif self.is_national_holiday(dt):
return True
else:
return False
# exit statuses
EXIT_HOLIDAY = 0
EXIT_WEEKDAY = 1
EXIT_ERROR = 2
def jpholidayp():
start_date = datetime.strptime(argvs[1], "%Y/%m/%d")
end_date = datetime.strptime(argvs[2], "%Y/%m/%d")
total_days = (end_date - start_date).days + 1 #inclusive 5 days
header = ["date","year","month","day","holiday","weekday"]
header_str = map(str,header)
print ",".join(header)
for day_number in range(total_days):
current_date = (start_date + timedelta(days = day_number)).date()
csv = []
csv.append(current_date)
csv.append(current_date.year)
csv.append(current_date.month)
csv.append(current_date.day)
csv.append(int(JpHoliday.is_holiday(current_date)))
csv.append(current_date.weekday())
csv_str = map(str,csv)
print ",".join(csv_str)
if __name__ == "__main__":
jpholidayp()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment