python日期加减比较问题请教

Python017

python日期加减比较问题请教,第1张

# time模块实现, 也是自带的

# 字符串不好计算~但是时间戳是固定的呀...

# 计算结果中, 假定今天24日, 输入24, 输出0天, 输入25, 输出-1天

import time

def f(tm):

    stamp = time.mktime(time.strptime(tm, "%Y%m%d"))

    diff = int((time.time() - stamp) // 86400)

    if diff <= 180:

        return {tm: str(diff)}

    else:

        d = {}

        while diff > 180:

            d[tm] = 180

            stamp += 180 * 86400

            diff = int((time.time() - stamp) // 86400)

            # 注意这里time.gmtime()返回的是0时区日期, 需要处理时区问题

            tm = time.strftime("%Y%m%d", time.gmtime(stamp - time.timezone))

        else:

            d[tm] = str(diff)

            return d

if __name__ == '__main__':

    tm = '20160325'

    print(f(tm))

    tm = '20171015'

    print(f(tm))

# 结果输出, 注意: 字典是没有固定顺序的

'''

{'20160921': 180, '20170320': 180, '20170916': '38', '20160325': 180}

{'20171015': '9'}

'''

import datetime#首行输入,导入模块

date1=datetime.date(year,month,day)#这里面year,month,day是代表年,月,日,年必须写成2021这种格式,都必须写成数字

date2=datetime.date(year,month,day)#同上,这个是第二个日期(后面的),上面的是第一个日期(前面的)

delta=date2-date1#这是两个日期相减,是一个时间差对象

diffdays=delta.total_seconds()//86400#差的秒数除以86400即可

print(diffdays)#打印差的天数

任何数据库本身都有自己的日期/时间函数,做日期比较,最好使用数据库函数比较。

这是因为,运行python的主机和数据库主机可能是不同的,系统时间也不一定同步。

不过,若是非要用python来实现,可以这样做:

#!/usr/bin/env python

# -*- coding: utf-8 -*-

import time

def now():

    return time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))

    

s = '2015-10-26 00:00:00'

if now() > s:

    print '过期'