current position:Home>Python notes (22): time module and calendar module

Python notes (22): time module and calendar module

2022-01-30 15:38:28 A bowl week

Little knowledge , Great challenge ! This article is participating in “ A programmer must have a little knowledge ” Creative activities .

Hello everyone , I am a A bowl week , One doesn't want to be drunk ( Internal volume ) The front end of the . If you are lucky enough to get your favor , I'm very lucky ~

stay Python There are many ways to deal with time and date in , Among them, the conversion date is the most common function .Python The time interval in is a floating-point decimal in seconds .

Time stamp

Python The current time is basically saved in time stamp . Time stamp unit is most suitable for date operation . however 1970 The date before the year cannot be expressed in this way . It's not good to be too far away ,UNIX and Windows Only to 2038 year .

Time stamp It means Greenwich mean time 1970 year 01 month 01 Japan 00 when 00 branch 00 The total number of seconds from seconds to the present . Generally speaking , A time stamp is a complete and verifiable data that can represent the existence of a data at a specific point in time . Its proposal is mainly to provide users with an electronic evidence , To prove the generation time of some data of the user .

Python Use in time Modular time Function to get the current timestamp

Sample code

import time
time_stamp = time.time()
print(" The current timestamp is :", time_stamp)  #  The current timestamp is : 1590585400.6808906
 Copy code 

time tuples

Python Many functions in are assembled with one element 9 Group numbers to process time .

Serial number attribute value
0 tm_year 2008
1 tm_mon 1 To 12
2 tm_mday 1 To 31
3 tm_hour 0 To 23
4 tm_min 0 To 59
5 tm_sec 0 To 61 (60 or 61 It's leap seconds )
6 tm_wday 0 To 6 (0 It's Monday )
7 tm_yday The day of the year ,1 To 366
8 tm_isdst Is it daylight saving time , Value has :1( Daylight saving time )、0( It's not summer time )、-1( Unknown ), Default -1

Reference resources Novice tutorial

Get the current time

Changing from the returned timestamp to a time tuple can use time Modular localtime() function ; time.gmtime([secs]) Also returns a time tuple

Sample code

import time
time_stamp = time.time()  #  Get the current timestamp 
localtime = time.localtime(time_stamp)
print(localtime)
# time.struct_time(tm_year=2020, tm_mon=5, tm_mday=27, tm_hour=21, tm_min=36, tm_sec=42, tm_wday=2, tm_yday=148, tm_isdst=0) 
 Copy code 

Format time

have access to time Modular asctime The function formats the time tuple into the simplest readable mode , If no parameter is given, it indicates the current time

time.ctime([secs]) This parameter accepts timestamp as the unit , Returns the readable mode of the date , Not giving parameters is equivalent to time.asctime()

Sample code

import time
time_stamp = time.time()
localtime = time.asctime(time.localtime(time_stamp))
print(" The current time is :", localtime)  #  The current time is : Wed May 27 21:47:48 2020
 Copy code 

Format date

Python Date formatting symbol in :

Symbol describe
%y A two digit number indicates the year (00-99)
%Y A four digit number indicates the year (0000-9999)
%m month (01-12)
%d One day in the month (1-31)
%H 24 Hours in hours (0-23)
%I 12 Hours in hours (01-12)
%M Minutes (00=59)
%S second (00-59)
%a Local simplified week name
%A Local full week name
%b Local simplified month name
%B Local full month name
%c Local corresponding date and time representation
%j One day in the year (001-366)
%p Local A.M. or P.M. The equivalent of
%U Weeks of the year (00-53) Sunday is the beginning of the week
%w week (0-6), Sunday is the beginning of the week
%W Weeks of the year (00-53) Monday is the beginning of the week
%x Local corresponding date representation
%X Local corresponding time representation
%Z Name of the current time zone
%% % The sign itself

time mktime( Structured time or complete 9 Byte element ) Function execution and gmtime(), localtime() Reverse operation , It receives struct_time Object as parameter , Returns the floating-point number of seconds for time . If the value entered is not a legal time , Will trigger OverflowError or ValueError.

Sample code

import time
time_stamp = time.time()
print(time_stamp)  # 1590590683.0062041
# 4 Number of years - month - Days  24 hourly : minute : second   What day of the week   The first few days of the year 
localtime = time.strftime("%Y-%m-%d %H:%M:%S %A %j", time.localtime(time_stamp))
print(localtime)  # 2020-05-27 22:44:43 Wednesday 148
#  Into a time tuple 
localtime_tuple = time.strptime(localtime, "%Y-%m-%d %H:%M:%S %A %j")
print(localtime_tuple)  # time.struct_time(tm_year=2020, tm_mon=5, tm_mday=27, tm_hour=22, tm_min=44, tm_sec=43, tm_wday=2, tm_yday=148, tm_isdst=-1)

#  Convert time tuples to seconds ( Time stamp )
time_stamp = time.mktime(localtime_tuple)
print(time_stamp)  # 1590590683.0  #  Basically equal to what you got at the beginning 
 Copy code 

obtain CPU Time

time.perf_counter() Return to the precise time of the timer ( Running time of the system ), Including the sleep time of the whole system . Because the reference point of the return value is undefined , therefore , Only the difference between the results of consecutive calls is valid .

time.process_time() Return to current process execution CPU Total time of , Does not include sleep time . Because the reference point of the return value is undefined , therefore , Only the difference between the results of consecutive calls is valid .

time.sleep() Function to delay the running of the calling thread , You can use the parameters secs Is the number of seconds , Indicates when the process was suspended .

Sample code

import time
#  Get the time when the system runs the function 
print(time.perf_counter())  # 0.0208446
time.sleep(2)
#  Read the time when the system runs the function ,
print(time.perf_counter())  # 2.0208952  #  The gap between the two is very small 
#  Get the current process execution  CPU  Total time of 
print(time.process_time())  # 0.015625  #  Does not include sleep time 
 Copy code 

Calendar module

Calendar Calendar module , The functions in this module are calendar related , For example, print the character calendar of a month

function describe
calendar.calendar(year,w=2,l=1,c=6) Returns the year Annual calendar ,3 Month and row , The interval is c. The daily width interval is w character . The length of each line is 21* W+18+2* C.l Is the number of lines per week .
calendar.month(year,month,w=2,l=1) Returns the year year month Monthly calendar , Two line headings , A Monday trip . The daily width interval is w character . The length of each line is 7* w+6.l Is the number of lines per week .
calendar.monthrange(year,month) Returns two integers . The first is the day of the month , The second is how many days of the month . What day of the week is from 0( Monday ) To 6( Sunday ).
calendar.leapdays(y1,y2) Back in the Y1,Y2 The total number of leap years between two years .
calendar.isleap(year) Determine if it's a leap year , It's leap year back True, Otherwise false.

Sample code

import calendar
#  Print this year's calendar 
print(calendar.calendar(2020))
#  Print this month's calendar 
print(calendar.month(2020, 5))
# monthrange Method 
print(calendar.monthrange(2020, 5))  # (4, 31)  # 5 The first day of the month is Friday, a total of 31 God , Because Monday is 0 therefore 4 It's Friday 
#  Calculation 1000 Year to 2000 The total number of leap years in 
print(calendar.leapdays(1000, 2000))  # 242
#  Judge whether this year is a leap year 
print(calendar.isleap(2020))  # True
 Copy code 

time.strftime(fmt[,tupletime]) Receive in time tuples , And returns the local time in a readable string , Format by fmt decision .

time.strptime(str,fmt='%a %b %d %H:%M:%S %Y') according to fmt The format parses a time string into a time tuple .

copyright notice
author[A bowl week],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/01/202201301538255726.html

Random recommended