1. 昨天、今天、明天
import datetime
from datetime import timedelta
now = datetime. datetime. now( )
today = now
yesterday = now - timedelta( days= 1 )
tomorrow = now + timedelta( days= 1 ) < br> < br>
2. 周、月、季的一天
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 )
3. 上一季度最后一天
from datetime import datetime
def getlastseason ( today) :
today = datetime. strptime( today, '%Y%m%d' )
quarter = ( today. month - 1 ) / 3 + 1
if quarter == 1 :
return datetime( today. year - 1 , 12 , 31 ) . strftime( '%Y%m%d' )
elif quarter == 2 :
return datetime( today. year, 3 , 31 ) . strftime( '%Y%m%d' )
elif quarter == 3 :
return datetime( today. year, 6 , 30 ) . strftime( '%Y%m%d' )
else :
return datetime( today. year, 9 , 30 ) . strftime( '%Y%m%d' )