python獲取當前時間的前一天,前一週,前一個月。
實用python的datetime.timedelta方法,避免了有的月份是30和31等不同的情況。
獲取前一個月的時間,方法實現:首先datetime.datetime.now
獲取當前時間,然後通過datetime.timedelta
獲取上一個月最後一天的datetime物件dayto
,最後用dayto
的資料初始化這個月的第一個天和最後一天的datetime物件。
import datetime
d = datetime.datetime.now()
def day_get(d):
oneday = datetime.timedelta(days=1)
day = d - oneday
date_from = datetime.datetime(day.year, day.month, day.day, 0, 0, 0)
date_to = datetime.datetime(day.year, day.month, day.day, 23, 59, 59)
print '---'.join([str(date_from), str(date_to)])
def week_get(d):
dayscount = datetime.timedelta(days=d.isoweekday())
dayto = d - dayscount
sixdays = datetime.timedelta(days=6)
dayfrom = dayto - sixdays
date_from = datetime.datetime(dayfrom.year, dayfrom.month, dayfrom.day, 0, 0, 0)
date_to = datetime.datetime(dayto.year, dayto.month, dayto.day, 23, 59, 59)
print '---'.join([str(date_from), str(date_to)])
def month_get(d):
"""
返回上個月第一個天和最後一天的日期時間
:return
date_from: 2016-01-01 00:00:00
date_to: 2016-01-31 23:59:59
"""
dayscount = datetime.timedelta(days=d.day)
dayto = d - dayscount
date_from = datetime.datetime(dayto.year, dayto.month, 1, 0, 0, 0)
date_to = datetime.datetime(dayto.year, dayto.month, dayto.day, 23, 59, 59)
print '---'.join([str(date_from), str(date_to)])
return date_from, date_to