python gets the time instance detail for the specified time difference

  • 2020-05-30 20:24:37
  • OfStack

python gets the time instance detail for the specified time difference

In the time of data analysis, it is often necessary to intercept the data within a certain range, such as the data within 3 days, two hours ago and other time requirements. Therefore, the functions that are often used in this part are modularized to facilitate reuse in the future. Here, also to share with you.


import time 
import sys 
reload(sys) 
 
def get_day_of_day(UTC=False, days=0, hours=0, miutes=0, seconds=0): 
 ''''''' 
 if days>=0,date is larger than today 
 if days<0,date is less than today 
 date format = "YYYY-MM-DD" 
 ''' 
 now = time.time() 
 timeNew = now + days*24*60*60 + hours*60*60 + miutes*60 + seconds 
 if UTC : 
 timeNew = timeNew + time.timezone 
 t = time.localtime(timeNew) 
 return time.strftime('%Y-%m-%d %H:%M:%S', t) 
 
# use UTC time   Two hours ago  
t = get_day_of_day(True,0,-2) 
print t 
# Local time  3 Days ago,  
t = get_day_of_day(False,-3) 
print t 
# Local time  3 Days later  
t = get_day_of_day(False,3) 
print t

Results obtained after operation:


2016-04-30 20:25:56 
2016-05-06 20:25:56

Thank you for reading, I hope to help you, thank you for your support of this site!


Related articles: