首页 > 编程语言 > 详细

python处理各种格式的时间

时间:2020-07-11 09:45:06      阅读:65      评论:0      收藏:0      [点我收藏+]

  每次用到都要百度,索性自己记下来了

 

 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):
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 则返回日期
27         @return: 返回时间
28         ‘‘‘
29         today_date = now_arr.shift(years=years,months=months,weeks=weeks,days=days,hours=hours)
30         today_date = today_date.format("YYYY-MM-DD") if is_date==True else today_date.format("YYYY-MM-DD HH:mm:ss")
31         return today_date
32 
33     @staticmethod
34     def beginning_and_end_of_month():
35         ‘‘‘
36         返回每月第一天和最后一天,格式 2020-07-01和2020-07-31
37         @return: start 每月第一天 ,end 每月最后一天
38         ‘‘‘
39         year = now.year
40         month = now.month
41         last_day = calendar.monthrange(year, month)[1]  ## 最后一天
42         start = datetime.date(year, month, 1)  # 每月第一天
43         end = datetime.date(year, month, last_day)  # 每月最后一天
44         return start, end
45 
46     @staticmethod
47     def timestamp_conversion_time(timenum, is_date=False):
48         ‘‘‘
49         10位或者13位的时间戳,转出正常格式的时间
50          is_date为True 返回日期格式:2020-07-09,False 返回时间格式:2020-07-09 09:30:13
51         @param timenum: 时间戳
52         @param is_date:  默认是False  为True 则返回日期
53         @return: 返回时间
54         ‘‘‘
55         time_num = int(timenum) if type(timenum) != int else timenum  # 不是int型转成int
56         timestamp = time_num if len(str(time_num)) == 10 else float(time_num / 1000)  # 10位数直接返回,不是10位数默认就是13位
57         time_array = time.localtime(timestamp)
58         other_style_time = time.strftime("%Y-%m-%d", time_array) if is_date == True else time.strftime(
59             "%Y-%m-%d %H:%M:%S", time_array)  # is_date为真返回日期,不然返回时间
60         return other_style_time
61 
62 
63 if __name__ == __main__:
64     a = VariousTime.get_specified_time(weeks=-2,is_date=True)
65     print(a)

 

python处理各种格式的时间

原文:https://www.cnblogs.com/yywy/p/13278785.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!