导入时间工具
import timeimport calendarimport datetimefrom dateutil import parser
时间戳转日期
def timestamp_datetime(tick, format='%Y%m%d'): tick = time.localtime(tick) dt = time.strftime(format, tick) return dt
日期转时间戳
def datetime_timestamp(dt, format='%Y%m%d'): tick = time.mktime(time.strptime(dt, format)) return int(tick)
日期转化(diff)
def datetime_shift(date, days, format='%Y%m%d'): tick = datetime_timestamp(date, format) tick = tick + days * 86400 date = timestamp_datetime(tick, format) return date
这个月第1天
def curr_month_first_day(date): date = date.replace('-', '')[0:8] time = datetime.date(int(date[0:4]), int(date[4:6]), int(date[6:8])) # 年,月,日 first_day = datetime.date(time.year, time.month, 1) first_day = str(first_day).replace('-', '') return first_day
上个月最后一天
def last_month_last_day(date): date = date.replace('-', '')[0:8] time = datetime.date(int(date[0:4]), int(date[4:6]), int(date[6:8])) # 年,月,日 first_day = datetime.date(time.year, time.month, 1) pre_month = first_day - datetime.timedelta(days=1) # timedelta是一个不错的函数 pre_month = str(pre_month).replace('-', '') return pre_month
上个月第1天
def last_month_first_day(date): date = date.replace('-', '')[0:8] time = datetime.date(int(date[0:4]), int(date[4:6]), int(date[6:8])) # 年,月,日 first_day = datetime.date(time.year, time.month, 1) pre_month = first_day - datetime.timedelta(days=1) first_day_of_pre_month = datetime.date(pre_month.year, pre_month.month, 1) first_day_of_pre_month = str(first_day_of_pre_month).replace('-', '') return first_day_of_pre_month
下个月第1天
def next_month_first_day(date): date = date.replace('-', '')[0:8] time = datetime.date(int(date[0:4]), int(date[4:6]), int(date[6:8])) # 年,月,日 first_day = datetime.date(time.year, time.month, 1) days_num = calendar.monthrange(first_day.year, first_day.month)[1] # 获取一个月有多少天 first_day_of_next_month = first_day + datetime.timedelta(days=days_num) # 当月的最后一天只需要days_num-1即可 first_day_of_next_month = str(first_day_of_next_month).replace('-', '') return first_day_of_next_month
返回两个时间点之间的日期集合
def date_collection(strStart, strEnd, format='%Y%m%d'): ds = parser.parse(strStart) de = parser.parse(strEnd) dates = [] while True: if (de - ds).days < 0: break dates.append(ds.strftime(format)) ds = ds + datetime.timedelta(days=1) return dates
获取星座
# 获取星座def get_constellation(birthday): month = int(birthday.replace('-', '')[4:6]) date = int(birthday.replace('-', '')[6:9]) dates = (21, 20, 21, 21, 22, 22, 23, 24, 24, 24, 23, 22) constellations = ("摩羯座", "水瓶座", "双鱼座", "白羊座", "金牛座", "双子座", "巨蟹座", "狮子座", "处女座", "天秤座", "天蝎座", "射手座", "摩羯座") if date < dates[month - 1]: return constellations[month - 1] else: return constellations[month]