Python實(shí)現(xiàn)日期判斷和加減操作詳解
python實(shí)現(xiàn)日期判斷和加減操作
#====================================================
#時(shí)間相關(guān)
#====================================================
def if_workday(day_str, separator=""):
"""
if a day is workday
:param day_str: string of a day
:param separator: separator of year, month and day, default is empty
:return: True: is workday; False: not workday
"""
spec = "%Y" + separator + "%m" + separator + "%d"
day = datetime.strptime(day_str, spec).date()
# Monday == 0 ... Sunday == 6
if day.weekday() in [0, 1, 2, 3, 4]:
return True
else:
return False
def if_weekend(day_str, separator=""):
"""
if a day is weekend
:param day_str: string of a day
:param separator: separator of year, month and day, default is empty
:return: True: is weekend; False: not weekend
"""
spec = "%Y" + separator + "%m" + separator + "%d"
day = datetime.strptime(day_str, spec).date()
# Monday == 0 ... Sunday == 6
if day.weekday() in [5, 6]:
return True
else:
return False
def is_week_lastday():
'''
判斷今天是否為周末,return the day of the week as an integer,Monday is 0 and Sunday is 6
:return:
'''
now = (datetime.datetime.utcnow() + datetime.timedelta(hours=8))
# 假如今天是周日
todayIndex = now.weekday()
# 如果今天是周日,則返回True
if todayIndex == 6:
print("todayIndex={},今天是周末...".format(todayIndex))
return True
else:
print("todayIndex={},今天是周 {},不是周末...".format(todayIndex,int(todayIndex+1)))
return False
def is_week_whichday(dayIndex=6):
'''
判斷今天一周的哪一天,周一為0,周末為6,return the day of the week as an integer,Monday is 0 and Sunday is 6
:return:
'''
now = (datetime.datetime.utcnow() + datetime.timedelta(hours=8))
# 假如今天是周日
todayIndex = now.weekday()
# 如果今天是周日,則返回True
if todayIndex == dayIndex:
print("todayIndex={},今天是周 {},不是周 {}...".format(todayIndex, int(todayIndex+1),int(dayIndex+1)))
return True
else:
print("todayIndex={},今天是周 {},不是周 {}...".format(todayIndex,int(todayIndex+1),int(dayIndex+1)))
return False
def is_month_lastday():
'''
# 判斷今天是否為月末
:return:
'''
# 獲得當(dāng)月1號(hào)的日期
start_date = datetime.date.today().replace(day=1)
# 獲得當(dāng)月一共有多少天(也就是最后一天的日期)
_, days_in_month = calendar.monthrange(start_date.year, start_date.month)
todayIndex = time.strftime("%d", time.localtime())
# 如果今天是周末,返回True
if int(todayIndex) == int(days_in_month):
print("start_date={},todayIndex={},days_in_month={},今天是月末...".format(start_date,todayIndex, days_in_month))
return True
else:
print("start_date={},todayIndex={},days_in_month={},今天不是月末...".format(start_date,todayIndex , days_in_month))
return False
def get_this_week_start():
'''
獲取本周第一天日期
:return:
'''
now = datetime.datetime.now()
this_week_start = now - timedelta(days=now.weekday())
this_week_end = now + timedelta(days=6 - now.weekday())
print('--- this_week_start = {} this_week_end = {}'.format(this_week_start, this_week_end))
print('--- this_week_start = {} '.format(this_week_start))
return this_week_start
def get_this_week_end():
'''
# 獲取本周最后一天日期
:return:
'''
now = datetime.datetime.now()
this_week_start = now - timedelta(days=now.weekday())
this_week_end = now + timedelta(days=6 - now.weekday())
print('--- this_week_start = {} this_week_end = {}'.format(this_week_start, this_week_end))
print('--- this_week_end = {}'.format(this_week_end))
return this_week_end
def get_last_month_start(now = datetime.datetime.now()):
now = datetime.datetime.strptime(now, "%Y-%m-%d")
# 本月第一天和最后一天
this_month_start = datetime.datetime(now.year, now.month, 1)
this_month_end = datetime.datetime(now.year, now.month + 1, 1) - timedelta(days=1) + datetime.timedelta(hours=23, minutes=59, seconds=59)
# print('--- this_month_start = {} this_month_end = {}'.format(this_month_start, this_month_end))
# 上月第一天和最后一天
last_month_end = this_month_start - timedelta(days=1)+ datetime.timedelta(hours=23, minutes=59, seconds=59)
last_month_start = datetime.datetime(last_month_end.year, last_month_end.month, 1)
# print('--- last_month_end = {} last_month_start = {}'.format(last_month_end, last_month_start))
print('--- last_month_start = {}'.format(last_month_start))
return last_month_start
def get_last_month_end(now = datetime.datetime.now()):
now = datetime.datetime.strptime(now, "%Y-%m-%d")
# 本月第一天和最后一天
this_month_start = datetime.datetime(now.year, now.month, 1)
this_month_end = datetime.datetime(now.year, now.month + 1, 1) - timedelta(days=1) + datetime.timedelta(hours=23, minutes=59, seconds=59)
# print('--- this_month_start = {} this_month_end = {}'.format(this_month_start, this_month_end))
# 上月第一天和最后一天
last_month_end = this_month_start - timedelta(days=1) + datetime.timedelta(hours=23, minutes=59, seconds=59)
last_month_start = datetime.datetime(last_month_end.year, last_month_end.month, 1)
# print('--- last_month_end = {} last_month_start = {}'.format(last_month_end, last_month_start))
print('--- last_month_end = {} '.format(last_month_end))
return last_month_end
def get_this_month_start(now = datetime.datetime.now()):
now = datetime.datetime.strptime(now, "%Y-%m-%d")
# 本月第一天和最后一天
this_month_start = datetime.datetime(now.year, now.month, 1)
this_month_end = datetime.datetime(now.year, now.month + 1, 1) - timedelta(days=1) + datetime.timedelta(hours=23, minutes=59, seconds=59)
# print('--- this_month_start = {} this_month_end = {}'.format(this_month_start, this_month_end))
# 上月第一天和最后一天
last_month_end = this_month_start - timedelta(days=1) + datetime.timedelta(hours=23, minutes=59, seconds=59)
last_month_start = datetime.datetime(last_month_end.year, last_month_end.month, 1)
# print('--- last_month_end = {} last_month_start = {}'.format(last_month_end, last_month_start))
print('--- this_month_start = {} '.format(this_month_start))
return this_month_start
def get_this_month_end(now = datetime.datetime.now()):
now=datetime.datetime.strptime(now, "%Y-%m-%d")
# 本月第一天和最后一天
this_month_start = datetime.datetime(now.year, now.month, 1)
# this_month_end = datetime.datetime(now.year, now.month + 1, 1) - timedelta(days=1) + datetime.timedelta(hours=23, minutes=59, seconds=59)
if now.month < 12:
this_month_end = datetime.datetime(now.year, now.month + 1, 1) - timedelta(days=1) + datetime.timedelta(hours=23, minutes=59, seconds=59)
elif now.month >= 12:
this_month_end = datetime.datetime(now.year, now.month , now.day+30) + datetime.timedelta(hours=23, minutes=59, seconds=59)
# print('--- this_month_start = {} this_month_end = {}'.format(this_month_start, this_month_end))
# 上月第一天和最后一天
last_month_end = this_month_start - timedelta(days=1) + datetime.timedelta(hours=23, minutes=59, seconds=59)
last_month_start = datetime.datetime(last_month_end.year, last_month_end.month, 1)
# print('--- last_month_end = {} last_month_start = {}'.format(last_month_end, last_month_start))
# print('--- this_month_end = {} '.format(this_month_end))
return str(this_month_end)
#從一個(gè)時(shí)間段獲取其中的每一天,可以自定義時(shí)間間隔
def get_every_day(start = '2018-01-01',end = '2021-01-01',daysCount=1):
'''
從一個(gè)時(shí)間段獲取其中的每一天,可以自定義時(shí)間間隔
:param start: str類(lèi)型,開(kāi)始時(shí)間,如:'2018-01-01'
:param end: str類(lèi)型,結(jié)束時(shí)間,如:'2021-01-01'
:param daysCount: int類(lèi)型,每一個(gè)時(shí)間間隔,默認(rèn)為1天
:return:
'''
datestart = datetime.datetime.strptime(start, '%Y-%m-%d')
dateend = datetime.datetime.strptime(end, '%Y-%m-%d')
date_list=[]
while datestart < dateend:
datestart += datetime.timedelta(days=daysCount)
date_str=str(datestart.strftime('%Y-%m-%d'))
# print('date_str={}'.format(date_str))
date_list.append(date_str)
print('date_list={}'.format(date_list))
return date_list
#從一個(gè)時(shí)間段獲取其中的每一月,可以自定義時(shí)間間隔
def getBetweenEveryMonth(begin_date,end_date):
date_list = []
begin_date = datetime.datetime.strptime(begin_date, "%Y-%m-%d")
end_date = datetime.datetime.strptime(end_date, "%Y-%m-%d")
# end_date = datetime.datetime.strptime(time.strftime('%Y-%m-%d', time.localtime(time.time())), "%Y-%m-%d")
while begin_date <= end_date:
date_str = begin_date.strftime("%Y-%m-%d")
begin_date = add_months_start(begin_date, 1)
date_end=get_this_month_end(date_str)
date_list.append((date_str+' 00:00:00',date_end))
print('date_list={}'.format(date_list))
return date_list
def add_months_start(dt, months):
month = int(dt.month - 1 + months)
year = int(dt.year + month / 12)
month = int(month % 12 + 1)
day = min(dt.day, calendar.monthrange(year, month)[1])
return dt.replace(year=year, month=month, day=day)
def add_months_end(dt, months):
month = int(dt.month - 1 + months)
year = int(dt.year + month / 12)
month = int(month % 12 + 1)
day = max(dt.day, calendar.monthrange(year, month)[1])
return dt.replace(year=year, month=month, day=day)到此這篇關(guān)于Python實(shí)現(xiàn)日期判斷和加減操作詳解的文章就介紹到這了,更多相關(guān)Python日期判斷 加減操作內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
利用Python實(shí)現(xiàn)自定義連點(diǎn)器
這篇文章主要介紹了如何利用Python實(shí)現(xiàn)自定義連點(diǎn)器,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-08-08
python GUI庫(kù)圖形界面開(kāi)發(fā)之PyQt5打開(kāi)保存對(duì)話框QFileDialog詳細(xì)使用方法與實(shí)例
這篇文章主要介紹了python GUI庫(kù)圖形界面開(kāi)發(fā)之PyQt5打開(kāi)保存對(duì)話框QFileDialog詳細(xì)使用方法與實(shí)例,需要的朋友可以參考下2020-02-02
python實(shí)現(xiàn)比較兩段文本不同之處的方法
這篇文章主要介紹了python實(shí)現(xiàn)比較兩段文本不同之處的方法,涉及Python針對(duì)文本與字符串的相關(guān)操作技巧,需要的朋友可以參考下2015-05-05
探索Python內(nèi)置數(shù)據(jù)類(lèi)型的精髓與應(yīng)用
本文探索Python內(nèi)置數(shù)據(jù)類(lèi)型的精髓與應(yīng)用,包括字符串、列表、元組、字典和集合。通過(guò)深入了解它們的特性、操作和常見(jiàn)用法,讀者將能夠更好地利用這些數(shù)據(jù)類(lèi)型解決實(shí)際問(wèn)題。2023-09-09
Python設(shè)計(jì)模式之單例模式實(shí)例
這篇文章主要介紹了設(shè)計(jì)模式中的單例模式Python實(shí)例,需要的朋友可以參考下2014-04-04
圖文詳解感知機(jī)算法原理及Python實(shí)現(xiàn)
感知機(jī)是二類(lèi)分類(lèi)的線性分類(lèi)模型,其輸入為實(shí)例的特征向量,輸出為實(shí)例的類(lèi)別(取+1和-1二值)。本文將為大家詳細(xì)講講感知機(jī)算法的原理及實(shí)現(xiàn),需要的可以參考一下2022-08-08
一篇文章帶你了解Python和Java的正則表達(dá)式對(duì)比
正則表達(dá)式有元字符及不同組合來(lái)構(gòu)成,通過(guò)巧妙的構(gòu)造正則表達(dá)式可以匹配任意字符串,并完成復(fù)雜的字符串處理任務(wù),希望本片文章能給你帶來(lái)幫助2021-09-09

