# 时间加减,月/日 import calendar import math def get_recent_month(dt, months): # 这里的months 参数传入的是正数表示往后推,负数表示往前推 month = dt.month - 1 + months year = dt.year + math.floor(month / 12) month = month % 12 + 1 day = min(dt.day, calendar.monthrange(year, month)[1]) recent_date = datetime.date(year, month, day).strftime('%Y%m%d') return recent_date def get_recent_day(dt, days): # days 负数是向前推,正数是向后推 # datetime.timedelta 两个时间之间的时间差 delta = datetime.timedelta(days=days) # 获取delta前的时间 beginPushDate = (dt + delta).strftime('%Y%m%d') return beginPushDate dt = datetime.datetime.strptime(str('20190101'), '%Y%m%d') # 当前日期前推3个月 print(get_recent_month(dt, -3)) # 当前日期后推3个月 print(get_recent_month(dt, 3)) # 当前日期前推3天 print(get_recent_day(dt, -3)) # 当前日期后推3天 print(get_recent_day(dt, 3))
#时间加减 周/日/时/分/毫秒 import datetime print(datetime.datetime.now()) #返回 2016-08-19 12:47:03.941925 print(datetime.date.fromtimestamp(time.time()) ) # 时间戳直接转成日期格式 2016-08-19 print(datetime.datetime.now() ) print(datetime.datetime.now() + datetime.timedelta(3)) #当前时间+3天 print(datetime.datetime.now() + datetime.timedelta(-3)) #当前时间-3天 print(datetime.datetime.now() + datetime.timedelta(hours=3)) #当前时间+3小时 print(datetime.datetime.now() + datetime.timedelta(minutes=30)) #当前时间+30分 c_time = datetime.datetime.now() print(c_time.replace(year=2019, month=3, day=20,hour=2, minute=3)) #时间替换
import datetime import calendar import math def get_now_dateTime(): ''' 获取当前时间 xx-xx-xx xx:xx:xx ''' time_now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') return time_now def get_endLastYear(endDate): ''' 获取上年年末,'20190321'上一年年末是'20181231' :param endDate: :return: ''' beginYear_temp = int(str(endDate)[0:4]) - 1 beginYear = str(beginYear_temp) + '1231' return beginYear def get_beginYearDate(endDate): ''' 本年年初,'20190321'年初'20190101' :param endDate: :return: ''' beginYear_temp = int(str(endDate)[0:4]) beginYear = str(beginYear_temp) + '0101' return beginYear def get_beginPushDate(bizDate, days): ''' 获取beginDate的days天前的时间 :param bizDate: :param days: days 负数是向前推,正数是向后推 :return: ''' dt = datetime.datetime.strptime(str(bizDate), '%Y%m%d') # datetime.timedelta 两个时间之间的时间差 delta = datetime.timedelta(days=days) # 获取delta前的时间 beginPushDate = (dt + delta).strftime('%Y%m%d') return beginPushDate def get_recent_month(bizDate, months): ''' 获取bizDate的months月前的时间 :param bizDate: :param months: months 参数传入的是正数表示往后推,负数表示往前推 :return: ''' dt = datetime.datetime.strptime(str(bizDate), '%Y%m%d') month = dt.month - 1 + months year = dt.year + math.floor(month / 12) month = month % 12 + 1 day = min(dt.day, calendar.monthrange(year, month)[1]) recent_date = datetime.date(year, month, day).strftime('%Y%m%d') return recent_date