?
在獲取貝殼分的時(shí)候用到了時(shí)間處理函數(shù),想要獲取上個(gè)月時(shí)間包括年、月、日等
# 方法一:
today = datetime.date.today() # 1. 獲取「今天」
first = today.replace(day=1) # 2. 獲取當(dāng)前月的第一天
last_month = first - datetime.timedelta(days=1) # 3. 減一天,得到上個(gè)月的最后一天
print(last_month.strftime("%Y%m")) # 4. 格式化成指定形式
# 方法二:
today = datetime.date.today() # 1. 獲取「今天」
last_month = today.replace(month=today.month - 1) # 2.獲取前一個(gè)月
print(last_month.strftime("%Y%m")) # 3. 格式化成指定形式
# 方法三: arrow包的使用(pip install arrow)
a = arrow.now() # 當(dāng)前本地時(shí)間
print(a.timestamp)
print(a.year)
print(a.month)
print(a.day)
print(a.date())
print(a.time())
print(a.shift(months=-4).format("YYYYMM"))
print(a.shift(months=1).format("YYYYMM"))
print(a.shift(hours=1))
# 生成arrow對(duì)象
print(arrow.get(1535113845))
print(arrow.get(datetime.date(2018, 7, 24)))
print(arrow.get("2018-08-11 12:30:56"))
運(yùn)行結(jié)果如下:
# 方法一
201906
# 方法二
201906
# 方法三
1562329178
2019
7
5
2019-07-05
20:19:38.573000
201903
201908
2019-07-05T21:19:38.573000+08:00
2018-08-24T12:30:45+00:00
2018-07-24T00:00:00+00:00
2018-08-11T12:30:56+00:00
所以想通過(guò)一個(gè)方法來(lái)兼容n種情況是極度困難的,內(nèi)部實(shí)現(xiàn)也會(huì)非常復(fù)雜,作為用戶使用起來(lái)必然也很混亂,我們需要根據(jù)自己的業(yè)務(wù)場(chǎng)景選取最合適的包來(lái)進(jìn)行處理。
聲明:本網(wǎng)頁(yè)內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問(wèn)題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com