python 时间处理的简单示例

前端之家收集整理的这篇文章主要介绍了python 时间处理的简单示例前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
对python这个高级语言感兴趣的小伙伴,下面一起跟随编程之家 jb51.cc的小编两巴掌来看看吧!

在实际中遇到一个时间处理问题,需要将 Sep 06,2014 19:30 (UTC 时间) 和 当前时间比较早晚,知道 此 2014-09-06 19:30 格式时间的运算。因此,在处理时,就想

先将sep 格式时间转化成 后面一个格式的时间样子,没有找到相关函数,于是自己简单的写了个程序,仅记于此,以备查询

代码如下:


# @param python 时间处理
# @author 编程之家 jb51.cc|www.www.jb51.cc 

# -*- coding: utf-8 -*- 
from datetime import date
from datetime import datetime
from datetime import timedelta
 
# # #如果是返回当前时间,可以简单的写成
# # time.localtime()
# # #这个返回UTC时间
# # time.gmtime()
# lt = time.localtime()
# tm = time.gmtime()
# ft = time.strftime('%Y-%m-%d %H-%M',lt)
# ft2 = time.strftime('%Y-%m-%d %H:%M',tm)
# print ft,ft2
# print '--------------------------------------------------------'
# now = datetime.datetime.now()
# now = now.replace(day = 1)
# print now
# print now.time()
#
# mytime = ['2014-09-06 20:19']
# #mytime2 = '2014-10-09 14:32'
# str = "".join(mytime)
# print str
# retime  = datetime.strptime(str,'%Y-%m-%d %H:%M')
# print retime
# retime = retime +timedelta(hours = 8)
# print retime
#
# tdtime = datetime.now()
# print tdtime
# if retime <= tdtime - timedelta(days = 7):
#     print "too early"
#
# #Sep 06,2014 19:30
 
monthdic = {'Jan':'01','Feb':'02','Mar':'03','Apr':'04','May':'05','Jun':'06','Jul':'07','Aug':'08','Sep':'09','Oct':'10','Nov':'11','Dec':'12'}
def time_format(timestr):
    timestr = timestr.replace(',','')
    #print timestr
    timelist = timestr.split()
    #print timelist
    mon = "".join(timelist[0])
    #print  mon
    timelist[0] = monthdic[mon]
    #print timelist
    mytime = "".join(timelist[2])+'-'+"".join(timelist[0])+'-'+"".join(timelist[1])+' '+ "".join(timelist[3])
    return mytime
if __name__ == '__main__':
    timestr = 'Sep 06,2014 19:30'
    str = time_format(timestr)
    print str      
    mytime  = datetime.strptime(str,'%Y-%m-%d %H:%M') 
    print mytime
    mytime = mytime +timedelta(hours = 8)
    print mytime  
    tdtime = datetime.now()
    print tdtime
    if mytime <= tdtime - timedelta(days = 7):
        print "too early"

# End www.jb51.cc
原文链接:https://www.f2er.com/python/527237.html

猜你在找的Python相关文章