代码
#!/usr/bin/python
# -*- coding: utf-8 -*-
import argparse, sys, time
from datetime import date, timedelta, datetime
from math import ceil
def pretty_dict(obj, indent=' '):
"""Copy From http://blog.csdn.net/handsomekang/article/details/40020667."""
def _pretty(obj, indent):
for i, tup in enumerate(obj.items()):
k, v = tup
#如果是字符串则拼上""
if isinstance(k, str): k = '"%s"'% k
if isinstance(v, str): v = '"%s"'% v
#如果是字典则递归
if isinstance(v, dict):
v = ''.join(_pretty(v, indent + ' '* len(str(k) + ': {')))#计算下一层的indent
#case,根据(k,v)对在哪个位置确定拼接什么
if i == 0:#开头,拼左花括号
if len(obj) == 1:
yield '{%s: %s}'% (k, v)
else:
yield '{%s: %s,\n'% (k, v)
elif i == len(obj) - 1:#结尾,拼右花括号
yield '%s%s: %s}'% (indent, k, v)
else:#中间
yield '%s%s: %s,\n'% (indent, k, v)
print(''.join(_pretty(obj, indent)))
parser = argparse.ArgumentParser(description="Generating date dimension data")
parser.add_argument('-s', '--startDate', help='Start date in YYYYMMDD format', required=False, dest='startDate')
parser.add_argument('-e', '--endDate', help='end date in YYYYMMDD format', required=False, dest='endDate')
argList = parser.parse_args()
if not len(sys.argv)>1:
startDate = endDate = date.today()
elif (argList.startDate > argList.endDate):
print("Input(s) Error: startDate date must be earlier than endDate")
sys.exit (1)
else:
try:
startDate = datetime.strptime(argList.startDate, '%Y%m%d').date()
endDate = datetime.strptime(argList.endDate, '%Y%m%d').date()
except ValueError:
print("Input(s) Error: must be valid date value in YYYYMMDD format")
sys.exit (1)
start = time.time()
while startDate <= endDate:
dateInfo = {
'DateKey': startDate.strftime('%Y-%m-%d'),
'FullYear': startDate.year,
'ShortYear': startDate.strftime('%y'),
'MonthNumberFull': startDate.month,
'MonthFull': startDate.strftime('%B'),
'WeekNumber': startDate.strftime('%U').lstrip("0"),
'MonthAbbr': startDate.strftime('%b'),
'WeekNumberFull': startDate.strftime('%U'),
'DayOfMonth': startDate.strftime('%d').lstrip("0"),
'DayOfMonthFull': startDate.strftime('%d'),
'DayOfWeek': startDate.isoweekday() % 7 + 1,
'DayOfWeekFull': startDate.strftime('%A'),
'DayOfWeekAbbr': startDate.strftime('%a'),
'ISODATE': startDate.strftime('%Y%m%d'),
'QuarterNumber': ceil(startDate.month/3.),
'FullDate': startDate.strftime('%d %B %Y'), # '1 January 2017',
'MonthAndYearAbbr': startDate.strftime('%b %Y'), # 'Jan 2017',
'YearAndWeek': startDate.strftime('%Y%U'), # '201701',
'YearAndMonthNumber': startDate.strftime('%Y%m')} # '201701'}
dateInfo['QuarterFull'] = 'Quarter ' + str(dateInfo['QuarterNumber'])
dateInfo['QuarterAbbr'] = 'Qtr ' + str(dateInfo['QuarterNumber'])
dateInfo['Quarter'] = 'Q' + str(dateInfo['QuarterNumber'])
dateInfo['QuarterAndYearNumber'] = startDate.strftime('%Y') + str(dateInfo['QuarterNumber'])
# print(dateInfo)
pretty_dict(dateInfo)
startDate = startDate + timedelta(1)
输出
# 默认输出当前日期
$ python genDateDimensionEcho.py
{"YearAndMonthNumber": "201712",
"MonthAbbr": "Dec",
"FullDate": "01 December 2017",
"QuarterAndYearNumber": "20174.0",
"MonthNumberFull": 12,
"DayOfWeekFull": "Friday",
"DayOfWeek": 6,
"QuarterAbbr": "Qtr 4.0",
"QuarterNumber": 4.0,
"DayOfWeekAbbr": "Fri",
"FullYear": 2017,
"WeekNumber": "48",
"QuarterFull": "Quarter 4.0",
"MonthAndYearAbbr": "Dec 2017",
"MonthFull": "December",
"Quarter": "Q4.0",
"DayOfMonthFull": "01",
"YearAndWeek": "201748",
"WeekNumberFull": "48",
"ISODATE": "20171201",
"DateKey": "2017-12-01",
"ShortYear": "17",
"DayOfMonth": "1"}
# 指定时间间隔
$ python genDateDimensionEcho.py -s 20171101 -e 20171102
{"YearAndMonthNumber": "201711",
"MonthAbbr": "Nov",
"FullDate": "01 November 2017",
"QuarterAndYearNumber": "20174.0",
"MonthNumberFull": 11,
"DayOfWeekFull": "Wednesday",
"DayOfWeek": 4,
"QuarterAbbr": "Qtr 4.0",
"QuarterNumber": 4.0,
"DayOfWeekAbbr": "Wed",
"FullYear": 2017,
"WeekNumber": "44",
"QuarterFull": "Quarter 4.0",
"MonthAndYearAbbr": "Nov 2017",
"MonthFull": "November",
"Quarter": "Q4.0",
"DayOfMonthFull": "01",
"YearAndWeek": "201744",
"WeekNumberFull": "44",
"ISODATE": "20171101",
"DateKey": "2017-11-01",
"ShortYear": "17",
"DayOfMonth": "1"}
{"YearAndMonthNumber": "201711",
"MonthAbbr": "Nov",
"FullDate": "02 November 2017",
"QuarterAndYearNumber": "20174.0",
"MonthNumberFull": 11,
"DayOfWeekFull": "Thursday",
"DayOfWeek": 5,
"QuarterAbbr": "Qtr 4.0",
"QuarterNumber": 4.0,
"DayOfWeekAbbr": "Thu",
"FullYear": 2017,
"WeekNumber": "44",
"QuarterFull": "Quarter 4.0",
"MonthAndYearAbbr": "Nov 2017",
"MonthFull": "November",
"Quarter": "Q4.0",
"DayOfMonthFull": "02",
"YearAndWeek": "201744",
"WeekNumberFull": "44",
"ISODATE": "20171102",
"DateKey": "2017-11-02",
"ShortYear": "17",
"DayOfMonth": "2"}