美文网首页
python获取月的第一天和上个月的同一天

python获取月的第一天和上个月的同一天

作者: Do_More | 来源:发表于2018-05-18 16:54 被阅读0次
    import datetime, time
    
    def lastMonth(date):
        year = date.year
        month = date.month
        day = date.day
        if month == 1 :
            month = 12
            year -= 1
        else :
            month -= 1
        if day == 31 and month in (4,6,9,11):
            day = 30
        if day > 28 and month == 2:
            day = 29 if year % 4 == 0 else 28
    
        last_beginday = datetime.datetime.strptime('%s-%s-%s'%(year, month, day), '%Y-%m-%d')
        last_sameday = datetime.datetime.strptime('%s-%s-%s %s:%s:%s'%(year, month, day, date.hour, date.minute, date.second), '%Y-%m-%d %H:%M:%S')
        last_begin_timestamp = last_beginday.strftime('%s')
        last_sameday_timestamp = last_sameday.strftime('%s')
        return last_begin_timestamp, last_sameday_timestamp
    
    def get_current_day_timestamp():
        time_string = datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d')
        timestamp = time.mktime(datetime.datetime.strptime(time_string, "%Y-%m-%d").timetuple())
        return timestamp
    
    last_begin_timestamp, last_sameday_timestamp = lastMonth(datetime.datetime.fromtimestamp(time.time()))
    current_day_timestamp = get_current_day_timestamp()
    print(last_begin_timestamp, last_sameday_timestamp, current_day_timestamp)
    

    相关文章

      网友评论

          本文标题:python获取月的第一天和上个月的同一天

          本文链接:https://www.haomeiwen.com/subject/teygdftx.html