日期函數的使用

 1 from  datetime  import  *
 2 today=datetime.today()
 3 now=datetime.now()
 4 
 5 #判斷今天是星期幾
 6 today.isoweekday()
 7 
 8 #計算一週之後是星期幾
 9 day=timedelta(days=7)
10 today+day
11 
12 #時間格式化
13 today.strftime('%Y年%m月%d日')
14 now.strftime('%Y年%m月%d日')
15 t1='20180802061528'
16 print(parse(t2).strftime('%Y-%m-%d  %H-%M-%S'))
17 2018-08-02  06-15-28
18 
19 
20 #從新轉化爲datetime.datetime格式
21 u=datetime.strptime('2020-06-08','%Y-%m-%d')
22 print(u)
23 datetime.datetime(2020, 6, 8, 0, 0)
24 
25 #從當前的時間減一天
26 one=timedelta(days=1)
27 today-one
28 
29 #爲當前時間加6個月
30 from  dateutil.relativedelta  import  relativedelta
31 date=today+relativedelta(months=6)
32 print(date)
33 datetime.datetime(2020, 12, 8, 22, 43, 24, 269837)
34 
35 #找出每個月最後一天
36 def   last_day_of_month(day):
37     next_month=day.replace(day=28)+timedelta(days=4)
38     return  next_month-timedelta(days=next_month.day)
39 last_day_of_month(datetime(2020,10,23))
相關文章
相關標籤/搜索