#15 time & datetime & calendar module

Preface

Starting from this section, record some commonly used built-in modules. The learning of modules may be boring, but the foundation is in this boring module. This section records time related modules!

I. time module

There are many modules for designing time in Python, but the most common one is the time module. First, let's look at all the methods of the time module:

In [3]: dir(time)
Out[3]:
['CLOCK_MONOTONIC', 'CLOCK_MONOTONIC_RAW', 'CLOCK_PROCESS_CPUTIME_ID', 'CLOCK_REALTIME', 'CLOCK_THREAD_CPUTIME_ID', '_STRUCT_TM_ITEMS', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'altzone', 'asctime', 'clock', 'clock_getres', 'clock_gettime', 'clock_settime', 'ctime', 'daylight', 'get_clock_info', 'gmtime', 'localtime', 'mktime', 'monotonic', 'perf_counter', 'process_time', 'sleep', 'strftime', 'strptime', 'struct_time', 'time', 'timezone', 'tzname','tzset']

There are many ways to analyze it

1. Acquisition time

In [19]: time.time()                      #Get the timestamp of the current time
Out[19]: 1549343780.962011

In [20]: time.localtime()                 # Gets the local time, returns the time tuple under the local time, but sets whether it is daylight saving time, tm_isdst Daylight saving time
Out[20]: time.struct_time(tm_year=2019, tm_mon=2, tm_mday=5, tm_hour=13, tm_min=16, tm_sec=27, tm_wday=1, tm_yday=36, tm_isdst=0)

In [21]: time.localtime(time.time())      # Parameter accepted as timestamp
Out[21]: time.struct_time(tm_year=2019, tm_mon=2, tm_mday=5, tm_hour=13, tm_min=16, tm_sec=39, tm_wday=1, tm_yday=36, tm_isdst=0)

In [22]: time.asctime()                   # Get format time
Out[22]: 'Tue Feb  5 13:17:23 2019'

In [23]: time.asctime(time.localtime())   # Parameter is struct_time format
Out[23]: 'Tue Feb  5 13:17:40 2019'

In [24]: time.ctime()                     # Get format time as above
Out[24]: 'Tue Feb  5 13:18:11 2019'

In [25]: time.gmtime()                    # with localtime,But return the time tuple in Greenwich astronomical time
Out[25]: time.struct_time(tm_year=2019, tm_mon=2, tm_mday=5, tm_hour=5, tm_min=18, tm_sec=18, tm_wday=1, tm_yday=36, tm_isdst=0)

2. Format date

In [28]: time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())    # Format adult-month-Day time:branch:Second form
Out[28]: '2019-02-05 13:26:27'

In [29]: time.strftime("%a %b %d %H:%M:%S %Y", time.localtime()) # Format as week month day hour:branch:Second year form
Out[29]: 'Tue Feb 05 13:26:47 2019'
In [33]: time.gmtime(time.time())        # Convert timestamps to struct_time format
Out[33]: time.struct_time(tm_year=2019, tm_mon=2, tm_mday=5, tm_hour=5, tm_min=40, tm_sec=15, tm_wday=1, tm_yday=36, tm_isdst=0)

In [34]: time.mktime(time.localtime())   # take struct_time formatTransformationTimestamp 
Out[34]: 1549345233.0
In [35]: time.strptime("2019/02/05","%Y/%m/%d")   # Convert formatted date to struct_time format
Out[35]: time.struct_time(tm_year=2019, tm_mon=2, tm_mday=5, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=1, tm_yday=36, tm_isdst=-1)

Supplement: time module date format symbol

%y      # Two digit year representation (00-99)
%Y      # Four digit year representation (000-9999)
%m      # Month (01-12)
%d      # Day of the month (0-31)
%H      # 24 Hours (0-23)
%I      # 12 Hours (01-12)
%M      # Minutes (00=59)
%S      # Seconds (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      # Day of the year (001-366)
%p      # local A.M.or P.M.Equivalents
%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
%%      # %Number itself

3. sleep

In [36]: time.sleep(3)   # Use time.sleep(Seconds) to get to sleep

4. Other methods

In [37]: time.altzone      # The number of offset seconds to return to the daylight saving time area in Western Greenwich. If the region is east of Greenwich it will return a negative value (e.g. Western Europe, including the UK). Enable region for daylight saving time to use
Out[37]: -28800

In [38]: time.clock()      # Returns the current CPU Time, used to measure the time consumption of different programs
Out[38]: 10.241939
 
In [39]: time.timezone     # Local time zone (daylight saving time not started) offset seconds from Greenwich(>0,America;<=0 Most of Europe, Asia, Africa)
Out[39]: -28800

In [40]: time.tzname       # Contains a pair of strings that vary according to the situation, namely, the name of the local time zone with daylight saving time, and the string without daylight saving time
Out[40]: ('CST', 'CST')

2. datetime module

The datetime module is not commonly used compared with the time module, but we still need to understand it

In [42]: datetime.datetime.now()   # Get the current time and directly return to the formatted time format, which is more user-friendly
Out[42]: datetime.datetime(2019, 2, 5, 13, 56, 28, 929415)

In [43]: datetime.datetime.now() + datetime.timedelta(5)         # Current time plus 5 days, default unit is day
Out[43]: datetime.datetime(2019, 2, 10, 14, 1, 14, 324972)

In [44]: datetime.datetime.now() + datetime.timedelta(-5)        # Current time minus 5 days
Out[44]: datetime.datetime(2019, 1, 31, 14, 1, 21, 15534)

In [45]: datetime.datetime.now() + datetime.timedelta(hours=5)   # Current time plus 5 hours
Out[45]: datetime.datetime(2019, 2, 5, 19, 1, 33, 334723)

In [46]: datetime.datetime.now() + datetime.timedelta(minutes=5) # Current time plus 5 minutes
Out[46]: datetime.datetime(2019, 2, 5, 14, 6, 46, 123465)

It can be seen that the datetime module is often used to calculate the addition and subtraction of dates, which has great advantages

III. calendar module

In [9]: import calendar

In [11]: print(calendar.calendar(2019))   # calendar.calendar(year,w=2,l=1,c=6),Returns the year Annual calendar, 3 months in a row, with an interval of c=6,The daily width interval is w=2 character,Length of each line is 21* W+18+2* C,l=1 Is the number of lines per week.
                                  2019

      January                   February                   March
Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su
    1  2  3  4  5  6                   1  2  3                   1  2  3
 7  8  9 10 11 12 13       4  5  6  7  8  9 10       4  5  6  7  8  9 10
14 15 16 17 18 19 20      11 12 13 14 15 16 17      11 12 13 14 15 16 17
21 22 23 24 25 26 27      18 19 20 21 22 23 24      18 19 20 21 22 23 24
28 29 30 31               25 26 27 28               25 26 27 28 29 30 31

       April                      May                       June
Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su
 1  2  3  4  5  6  7             1  2  3  4  5                      1  2
 8  9 10 11 12 13 14       6  7  8  9 10 11 12       3  4  5  6  7  8  9
15 16 17 18 19 20 21      13 14 15 16 17 18 19      10 11 12 13 14 15 16
22 23 24 25 26 27 28      20 21 22 23 24 25 26      17 18 19 20 21 22 23
29 30                     27 28 29 30 31            24 25 26 27 28 29 30

        July                     August                  September
Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su
 1  2  3  4  5  6  7                1  2  3  4                         1
 8  9 10 11 12 13 14       5  6  7  8  9 10 11       2  3  4  5  6  7  8
15 16 17 18 19 20 21      12 13 14 15 16 17 18       9 10 11 12 13 14 15
22 23 24 25 26 27 28      19 20 21 22 23 24 25      16 17 18 19 20 21 22
29 30 31                  26 27 28 29 30 31         23 24 25 26 27 28 29
                                                    30

      October                   November                  December
Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su
    1  2  3  4  5  6                   1  2  3                         1
 7  8  9 10 11 12 13       4  5  6  7  8  9 10       2  3  4  5  6  7  8
14 15 16 17 18 19 20      11 12 13 14 15 16 17       9 10 11 12 13 14 15
21 22 23 24 25 26 27      18 19 20 21 22 23 24      16 17 18 19 20 21 22
28 29 30 31               25 26 27 28 29 30         23 24 25 26 27 28 29
                                                    30 31
In [12]: calendar.firstweekday()   # Return to the first day of the week, 0 for Monday
Out[12]: 0

In [13]: calendar.isleap(2004)   # Test for leap month year
Out[13]: True

In [14]: calendar.isleap(2019)
Out[14]: False

In [15]: print(calendar.month(2019,1))   # calendar.month(year,month,w=2,l=1),Returns the year year month Monthly calendar, two line titles, one week line, daily width interval is w=2 The length of each line of characters is 7* w+6,l=1 Is the number of lines per week.
    January 2019
Mo Tu We Th Fr Sa Su
    1  2  3  4  5  6
 7  8  9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31

It's almost enough for calendar to master so much. If you need to check other methods, just check their help information.

Tags: Python

Posted on Sat, 30 Nov 2019 17:44:53 -0800 by sergeidave