每次用到都要百度,索性自己记下来了
1 import time 2 import arrow 3 import calendar, datetime 4 5 now = datetime.datetime.now() # 当前时间 格式:2020-07-10 09:17:39.350268 6 now_arr = arrow.now() # 当前时间 格式:2020-07-11T08:50:57.634640+08:00 7 8 9 class VariousTime: 10 ''' 11 返回各种格式的时间和日期 12 ''' 13 14 @staticmethod 15 def get_specified_time(years=0, months=0, weeks=0, days=0, hours=0, is_date=False, is_date_str=False): 16 17 ''' 18 获取指定年月日小时的指定时间 19 可以左右两边进行加减移位操作,加减的对象可以是年月日时分秒和星期 20 想指定哪个就传哪个,也可以是组合加减, 21 @param years: 年 int数字 默认0当前年份 22 @param months: 月 int数字 默认0当前月份 23 @param weeks: 周 int数字 默认0,例:今天周五,如为-1则返回上周五日期 24 @param days: 日 int数字 默认0当日 25 @param hours: 小时 int数字 默认0当前小时 26 @param is_date: 默认是False 为True 则返回日期2019-01-01 27 @param is_date_str: 默认是False 为True 则返回20190101 日期字符串 28 @return: 返回时间 29 ''' 30 today_date = now_arr.shift(years=years, months=months, weeks=weeks, days=days, hours=hours) 31 if is_date == True: 32 today_date = today_date.format("YYYY-MM-DD") 33 if is_date_str == True: 34 today_date = today_date.format("YYYYMMDD") 35 if is_date ==False and is_date_str==False: 36 today_date = today_date.format("YYYY-MM-DD HH:mm:ss") 37 38 return today_date 39 40 @staticmethod 41 def beginning_and_end_of_month(): 42 ''' 43 返回每月第一天和最后一天,格式 2020-07-01和2020-07-31 44 @return: start 每月第一天 ,end 每月最后一天 45 ''' 46 year = now.year 47 month = now.month 48 last_day = calendar.monthrange(year, month)[1] # 最后一天 49 start = datetime.date(year, month, 1) # 每月第一天 50 end = datetime.date(year, month, last_day) # 每月最后一天 51 return start, end 52 53 @staticmethod 54 def timestamp_conversion_time(timestamp_num, is_date=False): 55 ''' 56 10位或者13位的时间戳,转出正常格式的时间 57 is_date为True 返回日期格式:2020-07-09,False 返回时间格式:2020-07-09 09:30:13 58 @param timenum: 时间戳 59 @param is_date: 默认是False 为True 则返回日期 60 @return: 返回时间 61 ''' 62 time_num = int(timestamp_num) if type(timestamp_num) != 'int' else timestamp_num # 不是int型转成int 63 timestamp = time_num if len(str(time_num)) == 10 else float(time_num / 1000) # 10位数直接返回,不是10位数默认就是13位 64 time_array = time.localtime(timestamp) 65 other_style_time = time.strftime("%Y-%m-%d", time_array) if is_date == True else time.strftime( 66 "%Y-%m-%d %H:%M:%S", time_array) # is_date为真返回日期,不然返回时间 67 return other_style_time 68 69 70 if __name__ == '__main__': 71 a = VariousTime.get_specified_time(days=1,is_date=True) 72 print(a)