当前位置:网站首页>Time standard library

Time standard library

2022-07-07 21:54:00 Effort volume

Portal : Zero basis Python Learn programming courses by hand 2020 newest Python Zero foundation introductory course ( The end ) Want to learn Python This video is enough _ Bili, Bili _bilibili

time There are three time representations in the module

  1. Time stamp
  2. Structured time objects
  3. Format time string

Time stamp

import time

Time stamp 1970.1.1 Interval to specified time The unit is seconds

time.time() Generate timestamp of current time

time.time()-3600 Timestamp an hour ago

Structured time objects

st = time.localtime()
print(type(st))
print(st)

Output results :

<class 'time.struct_time'>
time.struct_time(tm_year=2022, tm_mon=6, tm_mday=17, tm_hour=16, tm_min=15, tm_sec=12, tm_wday=4, tm_yday=168, tm_isdst=0)

st Is essentially a tuple

print(' It's today {}-{:02d}-{}'.format(st[0],st[1],st[2]))
print(' It's today   week {}'.format(st.tm_wday+1))

Output results :

 It's today 2022-06-17
 It's today   week 5

The properties of an object are read-only Can't change

Format time string

print(time.ctime())

Output results :

Fri Jun 17 16:20:20 2022

strftime( Time format )'%Y-%m-%d %H:%M:%S'

print(time.strftime('%Y-%m-%d %H:%M:%S'))
print(time.strftime('%Y year %m month %d Japan  %H when %M branch %S second '))

Output results :

2022-06-17 16:25:44
2022 year 06 month 17 Japan  16 when 25 branch 44 second 

If you make a mistake :

UnicodeEncodeError: 'locale' codec can't encode character '\u5e74' in position 2: encoding error 

You need to add :

import locale
locale.setlocale(locale.LC_CTYPE,'chinese')

sleep:

t1 = time.time()
print('sleep begin...')
time.sleep(1.23)
print('sleep end')
t2 = time.time()
print(" Yes {:.3f} second ".format(t2-t1))

Conversion between three formats :

Time stamp Convert to Structured objects

# UTC Time 
time.gmtime(time.time())
time.gmtime()
# local
print(time.localtime())
print(time.localtime(time.time()))

Structured objects Convert to Time stamp

# mktime(st)
print(time.time())
print(time.mktime(time.localtime()))

Structured objects Convert to Format time string

# strftime(format,st)
print(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime()))
print(time.strftime('%Y-%m-%d %H:%M:%S',time.gmtime()))

Formatted string Convert to Structured time objects

# strptime(str, format)
strtime = '2020-07-25 13:23:18'
print(time.strptime(strtime,'%Y-%m-%d %H:%M:%S'))

 

 

原网站

版权声明
本文为[Effort volume]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/188/202207071424196988.html