python时间大小判断,相差天数秒数计算

#!/usr/bin/python
# -*- coding:utf-8 -*-

import time,datetime
import os,sys

#获取并检查外部传入参数
if(len(sys.argv)==2):
    bizDate=sys.argv[1]
    print "数据日期:",bizDate
    bizDate10 = bizDate[0:4] + '-' + bizDate[4:6] + '-' + bizDate[6:8]
    if len(bizDate) !=8:
       print "业务日期传参非法*********"
else:
     print "*********传参非法,请输入: YYYYMMDD*********"
     sys.exit(1)
       
#开始时间
Start_Time = bizDate10 + ' 13:55:00'
print '开始时间:  ' + Start_Time
Start_Time_int = int(time.mktime(time.strptime(Start_Time, "%Y-%m-%d %H:%M:%S")))
#print Start_Time_int

#当前时间
Current_Time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
print '当前时间:  ' + Current_Time
Current_Time_int = int(time.mktime(time.strptime(Current_Time, "%Y-%m-%d %H:%M:%S")))
#print Current_Time_int

#对比
if Current_Time_int > Start_Time_int:
   print "当前时间大于开始时间"
   #相差多少天
   Days = str((datetime.datetime.fromtimestamp(Current_Time_int)-datetime.datetime.fromtimestamp(Start_Time_int)).days)
   print "当前时间-开始时间相差(天): " + Days
   
   #相差多少秒
   Seconds1 = (datetime.datetime.fromtimestamp(Current_Time_int)-datetime.datetime.fromtimestamp(Start_Time_int)).seconds
   Seconds2 = int(Days)*24*3600
   Seconds = Seconds1 + Seconds2
   print "当前时间-开始时间相差(秒): " + str(Seconds)
   
elif Current_Time_int == Start_Time_int:
   print "当前时间等于开始时间"
   
else:
   print "当前时间小于开始时间"
   #相差多少天
   Days = str((datetime.datetime.fromtimestamp(Start_Time_int)-datetime.datetime.fromtimestamp(Current_Time_int)).days)
   print "当前时间-开始时间相差(天): " + Days
   #相差多少秒
   Seconds1 = (datetime.datetime.fromtimestamp(Start_Time_int)-datetime.datetime.fromtimestamp(Current_Time_int)).seconds
   Seconds2 = int(Days)*24*3600
   Seconds = Seconds1 + Seconds2
   print "当前时间-开始时间相差(秒): " + str(Seconds)

如果:

      当前时间小于开始时间时,可以认为取得是绝对值,相差的天数和秒数。

posted @ 2020-09-03 14:02  醉城、  阅读(3804)  评论(0编辑  收藏  举报