首页 >后端开发 >Python教程 >使用python时间处理方法

使用python时间处理方法

高洛峰
高洛峰原创
2017-03-17 15:49:371028浏览

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

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

代码如下:

# -*- 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 = {&#39;Jan&#39;:&#39;01&#39;, &#39;Feb&#39;:&#39;02&#39;, &#39;Mar&#39;:&#39;03&#39;, &#39;Apr&#39;:&#39;04&#39;, &#39;May&#39;:&#39;05&#39;, &#39;Jun&#39;:&#39;06&#39;, &#39;Jul&#39;:&#39;07&#39;, &#39;Aug&#39;:&#39;08&#39;, &#39;Sep&#39;:&#39;09&#39;, &#39;Oct&#39;:&#39;10&#39;, &#39;Nov&#39;:&#39;11&#39;, &#39;Dec&#39;:&#39;12&#39;}
def time_format(timestr):
    timestr = timestr.replace(&#39;,&#39;,&#39;&#39;)
    #print timestr
    timelist = timestr.split()
    #print timelist
    mon = "".join(timelist[0])
    #print  mon
    timelist[0] = monthdic[mon]
    #print timelist
    mytime = "".join(timelist[2])+&#39;-&#39;+"".join(timelist[0])+&#39;-&#39;+"".join(timelist[1])+&#39; &#39;+ "".join(timelist[3])
    return mytime
if name == &#39;main&#39;:
    timestr = &#39;Sep 06, 2014 19:30&#39;
    str = time_format(timestr)
    print str      
    mytime  = datetime.strptime(str,&#39;%Y-%m-%d %H:%M&#39;) 
    print mytime
    mytime = mytime +timedelta(hours = 8)
    print mytime  
    tdtime = datetime.now()
    print tdtime
    if mytime <= tdtime - timedelta(days = 7):
        print "too early"

           

以上是使用python时间处理方法的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn