Explain the common methods of time and datetime in python in detail

  • 2021-07-10 20:29:02
  • OfStack

1. Common methods of time:


import time,datetime

#  Time has 3 Presentation methods: timestamp, time tuple, formatted time 
print(time.time())# Current timestamp 
print(int(time.time()))
print(time.strftime('%Y-%m-%d %H:%M:%S'))# Formatted time 
print(time.strftime('%Y-%m-%d'))
print(time.strftime('%H:%M:%S'))
print(time.gmtime())# Gets the time tuple of the standard time zone. If a timestamp is passed in, it is converted into a time tuple 
print(time.gmtime(1516194265))

Implementation results:

1516197631.0563018
1516197631
2018-01-17 22:00:31
2018-01-17
22:00:31
time.struct_time(tm_year=2018, tm_mon=1, tm_mday=17, tm_hour=14, tm_min=0, tm_sec=31, tm_wday=2, tm_yday=17, tm_isdst=0)
time.struct_time(tm_year=2018, tm_mon=1, tm_mday=17, tm_hour=13, tm_min=4, tm_sec=25, tm_wday=2, tm_yday=17, tm_isdst=0)

2. Common methods of 2. datetime:


#  Use datetime And time Get the current time 
now1 = datetime.datetime.now()
now2=time.strftime('%Y-%m-%d %H:%M:%S')
print(now1)
print(now2)
now = datetime.datetime.now()
d1 = now - datetime.timedelta(hours=1)# Before getting 1 Hours 
d2 = now - datetime.timedelta(days=1)# Before getting 1 Days 
print(now)
print(d1)

Implementation results:

2018-01-17 22:03:04.686923
2018-01-17 22:03:04
2018-01-17 22:03:04.687486
2018-01-17 21:03:04.687486

3. Use datetime to get the length of code execution


#  Using timestamps to get code execution time 
s_time = time.time()
for i in range(0,10):
  time.sleep(1)
e_time=time.time()

print(' Code run time is: ',e_time - s_time)

Implementation results:

Code run time: 10.003105163574219

4. Interconversion of timestamps and strings


#  String formatting time conversion timestamp 
str_time = '2018-1-17'
print(time.mktime(time.strptime(str_time,'%Y-%m-%d')))
#  The timestamp is converted to a formatted time string 
gsh_time= time.time()
print(time.strftime('%Y-%m-%d',time.localtime(gsh_time)))
# datetime Object to timestamp 
dt = datetime.datetime.now()
print(time.mktime(dt.timetuple()))
#  The timestamp is converted to datetime Object 
sjc_time = time.time()
print(datetime.datetime.fromtimestamp(sjc_time))

Implementation results:

1516118400.0
2018-01-17
1516198008.0
2018-01-17 22:06:48.944055

Summarize


Related articles: