datetime
字串與日期轉換
from datetime import date, timedelta, datetime
# 將字串轉換為日期,可比大小,型態為datetime.datetime
date_date = datetime.strptime('2017-10-10','%Y-%m-%d')
# 將datetime.datetime轉換為str
date_str = date_date.strftime('%Y-%m-%d')
日期加減
#python3
from datetime import date, timedelta, datetime
# 將字串轉換為日期,可比大小
date=datetime.strptime('2017-10-10','%Y-%m-%d')
# 昨天
new_date_str = (date.today()-timedelta(1)).strftime('%Y-%m-%d') # 字串型態
new_date = datetime.strptime(new_date_str, '%Y-%m-%d') # 日期型態
# 昨天再往前推十天
old_date_str = (date.today()-timedelta(10)).strftime('%Y-%m-%d')
old_date = datetime.strptime(old_date_str, '%Y-%m-%d')
print('today: ', date.today())
print('new: ', new_date_str)
print('old: ', old_date_str)
delta = int((new_date - old_date).days)
print('delta: ', delta)
# 用迴圈列出區間所有日期
for i in range(delta+1):
print(i, new_date - timedelta(i))
輸出
today: 2018-06-28
new: 2018-06-27
old: 2018-06-18
delta: 9
0 2018-06-27 00:00:00
1 2018-06-26 00:00:00
2 2018-06-25 00:00:00
3 2018-06-24 00:00:00
4 2018-06-23 00:00:00
5 2018-06-22 00:00:00
6 2018-06-21 00:00:00
7 2018-06-20 00:00:00
8 2018-06-19 00:00:00
9 2018-06-18 00:00:00
取得當前日期
#取得當前時間,可指定格式
import time
print(time.strftime("%Y-%m-%d_%H:%M:%S"))
# 2018-10-12_13:43:48 type=str
from datetime import date
print(date.today())
# 2018-10-12 type=datetime.date
參考來源: http://blog.webgolds.com/view/6
date vs datetime
不同type無法比較
from datetime import date, timedelta, datetime
# 將字串轉換為日期,可比大小
date_date = datetime.strptime('2017-10-10', '%Y-%m-%d')
if date_date > date.today():
print('ok')
# error:can't compare datetime.datetime to datetime.date
參考連結: http://wiki.alarmchang.com/index.php?title=使用Python_做日期的加減(相差幾天)(datetime\
月份區間處理
from datetime import datetime, date, timedelta
import calendar
# 取得該月的天數(n),並從該日往後n天
def get_month_range(start_input=None, mode='str'):
if mode != 'str' and mode != 'datetime':
print('mode must be str or datetime')
sys.exit()
if start_input is None:
start_date = date.today().replace(day=1) # 變成1號
else:
start_date = datetime.strptime(start_input, '%Y-%m-%d')
start_date = start_date.replace(day=1)
_, days_in_month = calendar.monthrange(start_date.year, start_date.month) # 該月的天數
end_date = start_date + timedelta(days=days_in_month - 1) # 從一號推算出最後一號
start_date = start_date.strftime('%Y-%m-%d')
end_date = end_date.strftime('%Y-%m-%d')
if mode == 'datetime':
start_date = datetime.strptime(start_date, '%Y-%m-%d')
end_date = datetime.strptime(end_date, '%Y-%m-%d')
return [start_date, end_date]
# 判斷兩個時間區間之間是否有交集
def match_month_range(old_date, new_date, month_start, month_end):
match = False
date_delta = (new_date - old_date).days
for i in range(0, date_delta + 1):
date_now = old_date + timedelta(days=i)
# print(date_now)
if month_start <= date_now <= month_end:
# print('ok', date_now)
match = True
break
return match
# 取得月或日
start_date.month
Last updated