1. Time module
Timestamp
formatted time in seconds since Unix year 1
1) Get the current timestamp
import time print (time.time()) #Get the current timestamp
2) output after some time
import time time.sleep( 10 ) print ( ' haha ' ) # print after 10 seconds
3) Get the formatted time
import time today =time.strftime( ' %Y-%m-%d %H:%M:%S ' ) #Get the formatted time print (today)
4) The default time is the standard time zone
import time print(time.gmtime())
5) Get the current time zone time
import time print (time.localtime()) #Get the time in the current time zone
6) Convert the timestamp to a time tuple, and then convert the time tuple to a formatted time
import time s =time.localtime(1514198608) #Convert the timestamp to a time tuple print (time.strftime( ' %Y-%m-%d %H:%M:%S ' ,s)) #Then convert the time tuple Group conversion to formatted time
7) The current formatted time is returned by default. If a timestamp is passed in, convert the timestamp into a formatted time and return
import time
def timestamp_to_fomat(timestamp=None,format='%Y-%m-%d %H:%M:%S'): if timestamp: time_tuple=time.localtime(timestamp) res=time.strftime(format,time_tuple) else: res=time.strftime(format) return res print(timestamp_to_fomat()) print(timestamp_to_fomat(1514198608))
8) Convert the formatted time to a time tuple, and then convert the time tuple to a timestamp
import time tp =time.strptime( ' 2018-4-21 ' , ' %Y-%m-%d ' ) #Convert the formatted time into a time tuple print (time.mktime(tp)) #Convert the time element Convert groups to timestamps
9) The function does not pass parameters, returns the timestamp of the current time, and returns the timestamp of the parameter if the parameter is passed in
import time def strTimestamp(str=None,format='%Y%m%d%H%M%S'): if str: tp =time.strptime(str,format) #Convert to time tuple res=time.mktime(tp) #Convert to timestamp else : res =time.time() #The timestamp of the current time is taken by default return int(res) print(strTimestamp()) print(strTimestamp('20181229183859')) print(strTimestamp('2018-12-29','%Y-%m-%d'))
2. datetime module
1) Get the current time
import datetime print (datetime.datetime.today()) #Get the current time
2) Get the time of the day, accurate to the day
import datetime print (datetime.date.today()) #accurate to days
3) Get the time after a few days
import datetime res =datetime.date.today()+datetime.timedelta(days=5) #Get the time after 5 days print (res) #You can also write minutes, weeks, seconds time
4) Get the time a few days ago
import datetime res =datetime.date.today()+datetime.timedelta(days=-5) #Get the time 5 days ago print (res)
5) Get the time a few days ago (output format custom)
import datetime res =datetime.date.today()+datetime.timedelta(days=-5) #Get the time 5 days ago print (res.strftime( ' %Y%m%d ' ))