import datetime # 將字符串轉換成時間 start_time = '201808201000' now_datetime = datetime.datetime.strptime(start_time, '%Y%m%d%H%M') 其中"%Y%m%d %H%M%S"爲time字符串的時間格式 Y爲年,m爲月,d爲天,H爲小時,M爲分鐘,S爲秒,執行轉化結果以下 2018-08-20 10:00:00 若是咱們要加的時間是天,當前時間加上datetime.timedelta(days=1)。datetime的timedelta方法實現 low_datetime = now_datetime + datetime.timedelta(days=1)
若是要加的時間是小時則以下,當前時間加上datetime.timedelta(hourpython
s=1)ide
low_datetime = now_datetime + datetime.timedelta(hours=1)
若是要加的時間是分鐘則以下,當前時間加上datetime.timedelta(minutes=1)this
low_datetime = now_datetime + datetime.timedelta(minutes=1) print(low_datetime)
若是加的時間是秒的話,以下當前時間加上datetime.timedelta(seconds=1)code
low_datetime = now_datetime + datetime.timedelta(seconds=1) print(low_datetime)
時間轉換成字符串字符串
low_datetime = now_datetime - datetime.timedelta(minutes=2) low_datetime = low_datetime.strftime('%Y%m%d%H%M') print(low_datetime)
import datetime from datetime import timedelta now = datetime.datetime.now() #今天 today = now #昨天 yesterday = now - timedelta(days=1) #明天 tomorrow = now + timedelta(days=1)<br><br>#當前季度 now_quarter = now.month / 3 if now.month % 3 == 0 else now.month / 3 + 1 #本週第一天和最後一天 this_week_start = now - timedelta(days=now.weekday()) this_week_end = now + timedelta(days=6-now.weekday()) #上週第一天和最後一天 last_week_start = now - timedelta(days=now.weekday()+7) last_week_end = now - timedelta(days=now.weekday()+1) #本月第一天和最後一天 this_month_start = datetime.datetime(now.year, now.month, 1) this_month_end = datetime.datetime(now.year, now.month + 1, 1) - timedelta(days=1) #上月第一天和最後一天 last_month_end = this_month_start - timedelta(days=1) last_month_start = datetime.datetime(last_month_end.year, last_month_end.month, 1) #本季第一天和最後一天 month = (now.month - 1) - (now.month - 1) % 3 + 1 this_quarter_start = datetime.datetime(now.year, month, 1) this_quarter_end = datetime.datetime(now.year, month + 3, 1) - timedelta(days=1) #上季第一天和最後一天 last_quarter_end = this_quarter_start - timedelta(days=1) last_quarter_start = datetime.datetime(last_quarter_end.year, last_quarter_end.month - 2, 1) #本年第一天和最後一天 this_year_start = datetime.datetime(now.year, 1, 1) this_year_end = datetime.datetime(now.year + 1, 1, 1) - timedelta(days=1) #去年第一天和最後一天 last_year_end = this_year_start - timedelta(days=1) last_year_start = datetime.datetime(last_year_end.year, 1, 1)