Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
日付特徴を作成する/ create datetime feature.
from datetime import datetime, date, timedelta
import calendar
import jpholiday
import numpy as np
# 2019/6/30から年月日をパース
timestamp_str = '2019/6/30'
t = datetime.strptime(timestamp_str, '%Y/%m/%d')
# 月:0 ~ 日:6 のint型で取得
weekday = t.weekday()
# 祝日フラグ
holidayflag = jpholiday.is_holiday(t.date())
# 次の日が休日
beginofh = jpholiday.is_holiday(t.date()+ timedelta(days=1)) or (t.date() + timedelta(days=1)).weekday()>4
# 次の日が平日
endofh = not(jpholiday.is_holiday(t.date()+ timedelta(days=1))) and (t.date() + timedelta(days=1)).weekday()==0
# 元旦から何日目か
dayofyear = t.timetuple().tm_yday
# 年と週番号(元旦から第何週目か)
year, weekofyear, _ = t.isocalendar()
# 月と日
month, day = t.month, t.day
# 年度始めから何日目か
frombiginofyear = (t.date() - datetime(t.year-(t.month<4)*1, 4, 1).date()).days
# 特定の年月の平日・休日一覧を取得
def getdaytypelistfromYM(year, month):
weekdays, holydays = [], []
for i in range(calendar.monthrange(year, month)[1]):
if datetime(year, month, i+1).weekday()<5 and not jpholiday.is_holiday(date(year, month, i+1)):
# 平日の場合
weekdays += [i+1]
else:
# 休日・祝日
holydays += [i+1]
return weekdays, holydays
weekdays, holydays = getdaytypelistfromYM(year, month)
# その月に平日と休日が何日あるか
weekdays, holydays = getdaytypelistfromYM(year, month)
numofweekdays, numofholydays = len(weekdays), len(holydays)
# 一年前の今日に一番近い同じ曜日の日付
nearestwd = date(year-1, month, day)
for i in range(4):
# 一年前 + i日後の曜日と比較
if weekday == (nearestwd + timedelta(days=i)).weekday():
nearestwd = date(year-1, month, day) + timedelta(days=i)
break
# 一年前 - i日後の曜日と比較
if weekday == (nearestwd + timedelta(days=-i)).weekday():
nearestwd = date(year-1, month, day) + timedelta(days=-i)
break
# 特定の日付からの経過日数
daydiff = (t.date() - datetime(2017, 6, 30).date()).days
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.