python處理各種格式的時間


  每次用到都要百度,索性自己記下來了

 

 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)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM