Python 日期相關問題總結

2021-10-11 04:21:48 字數 3226 閱讀 3010

比如:

計算過去兩年/一年/半年/三個月/乙個月內的資料量

計算合同預計簽署日期在未來一年內的資料量

def

past24mons

(time)

: time = time.replace(

'-','')

past24ago =

'{}{}'

.format

(int

(datetime.datetime.now(

).strftime(

'%y%m%d')[

:4])

-2, datetime.datetime.now(

).strftime(

'%m%d'))

return time >= past24ago

def

past12mons

(time)

: time = time.replace(

'-','')

past12ago =

'{}{}'

.format

(int

(datetime.datetime.now(

).strftime(

'%y%m%d')[

:4])

-1, datetime.datetime.now(

).strftime(

'%m%d'))

return time >= past12ago

def

one_year_ago

(time)

: date =

for i in time:

tmp =

str(

int(i[:4

])-1

)+ i[4:

] date[i]

= tmp

return date

from datetime import datetime,timedelta

from dateutil.relativedelta import relativedelta

def

past6mon

(time)

: time = time.replace(

'-','')

past6ago = datetime.date.today(

)- datetime.timedelta(days=

180)

past6ago = past6ago.strftime(

'%y%m%d'

)return time >= past6ago

defpast1mon

(time)

: time = time.replace(

'-','')

past1ago = datetime.date.today(

)- datetime.timedelta(days=30)

past1ago = past1ago.strftime(

'%y%m%d'

)return time >= past1ago

# 獲得當前時間

now_time = datetime.now(

)print

(now_time,

"當前時間"

)# 方法一

defchange_time

(time_str, days=

0, hours=

0, minutes=0)

:iftype

(time_str)

==str

: time_str = datetime.strptime(time_str,

'%y-%m-%d %h:%m:%s'

) ret = time_str + timedelta(days=days, hours=hours, minutes=minutes)

return ret

# 7天後

ret1 = change_time(now_time, days=7)

print

(ret1,

"7天後"

)# 方法二

defdelay_time

(time_str, years=

0, months=

0, days=

0, hours=

0, minutes=

0, seconds=0)

:iftype

(time_str)

==str

: time_str = datetime.strptime(time_str,

'%y-%m-%d %h:%m:%s'

) ret = time_str + relativedelta(years=years, months=months, days=days, hours=hours, minutes=minutes, seconds=seconds)

return ret

# 1個月前

ret2 = delay_time(now_time, months=-1

)print

(ret2,

'乙個月前'

)# 注意: relativedelta 還有一種用法

ret3 = now_time + relativedelta(day=10)

# 注意這裡是day, 上邊是days

print

(ret3)

# 此時獲得的時間是10號的, 也就是上邊的day是幾他就是幾號,

# 有意思的是, 你是平年2月傳乙個31, 得到的結果是28

2020-12

-2516:

08:15.946219 當前時間

2021-01

-0116:

08:15.946219

7天後2020-11

-2516:

08:15.946219 乙個月前

2020-12

-1016:

08:15.946219

iOS 日期相關總結

nsstring thu oct 16 17 06 25 0800 2014 dateformat eee mmm dd hh mm ss z yyyy nsdateformatter fmt nsdateformatteralloc init 如果是真機除錯,轉換這種歐美時間,需要設定locale...

Python 日期格式相關

今天看網上乙個說中文日期的問題.自己試了下.1 2 3 4 5 6 7 8 9 10 coding gb2312 importdatetime,time now time.strftime y年 m月 d日 h時 m分 s秒 time.localtime decode utf 8 now time....

python 日期相關操作

資料集3的特徵為 取 線上資料中領券和用券日期大於3月15日和小於6月30日的 feature3 off train off train.date 20160315 off train.date 20160630 off train.date null off train.date received...