在實際中遇到一個時間處理問題,需要將 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 = {'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"
#
以上是使用python時間處理方法的詳細內容。更多資訊請關注PHP中文網其他相關文章!