Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Python3 date and time


May 10, 2021 Python3


Table of contents


Python3 date and time

Python programs can handle dates and times in many ways, and converting date formats is a common feature.

Python provides a time and calendar module that can be used to format dates and times.

The interval is a small number of floating points in seconds.

Each timestamp is expressed in terms of how long it has been since midnight (calendar) on January 1, 1970.

There are many functions under Python's time module that convert common date formats. As the function time.time() is used to get the current timestamp, the following example:

#!/usr/bin/python3
import
time; # 引入time模块

ticks
= time.time()
print ("当前时间戳为:", ticks)

The above example output results:

当前时间戳为: 1459996086.7115328

Timestamp units are best suited for date operations. B ut the dates before 1970 cannot be expressed in this way. Too distant a date, UNIX and Windows only support until 2038.


What is a time group?

Many Python functions process time with 9 sets of numbers assembled in one meta:

Serial number Field Value
0 4-digit year 2020
1 Month 1 to 12
2 Day 1 to 31
3 Hours 0 to 23
4 Minutes 0 to 59
5 Seconds 0 to 61 (60 or 61 is a leap second)
6 The first day of the week 0 to 6 (0 is Monday)
7 The first few days of the year 1 to 366 (Julian calendar)
8 Daylight saving time -1, 0, 1, -1 is the flag that determines whether it is daylight saving time

The above is struct_time the two metagroups. This structure has the following properties:

Serial number Property Value
0 tm_year 2020
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 is a leap second)
6 tm_wday 0 to 6 (0 is Monday)
7 tm_yday The first day of the year, 1 to 366
8 tm_isdst Whether it is daylight saving time, the values are: 1 (daylight saving time), 0 (not daylight saving time), -1 (unknown), default -1


Gets the current time

Switch from the time drop that returns floats to the time group, as long as the floats are passed to a function such as localtime.

#!/usr/bin/python3
import time

localtime
= time.localtime(time.time())
print
("本地时间为 :", localtime)

The above example output results:

本地时间为 : time.struct_time(tm_year=2016, tm_mon=4, tm_mday=7, tm_hour=10, tm_min=28, tm_sec=49, tm_wday=3, tm_yday=98, tm_isdst=0)

Gets the time it was formatted

You can choose from a variety of formats depending on your needs, but the simplest function to get readable time patterns is asctime():

#!/usr/bin/python3
import
time

localtime
= time.asctime( time.localtime(time.time()) )
print
("本地时间为 :", localtime)

The above example output results:

本地时间为 : Thu Apr  7 10:29:13 2020

Format the date

We can format the date using the strftime method of the time module:

time.strftime(format[, t])
#!/usr/bin/python3
import
time

# 格式化成2020-03-20 11:45:39形式

print
(time.strftime("%Y-%m-%d %H:%M:%S", time .localtime()))

# 格式化成Sat Mar 28 22:24:24 2020形式
print (time.strftime("%a %b %d %H:%M:%S %Y", time. localtime()))

# 将格式字符串转换为时间戳

a
= "Sat Mar 28 22:24:24 2020"
print (time.mktime(time. strptime(a,"%a %b %d %H:%M:%S %Y")))

The above example output results:

2020-04-07 10:29:46
Thu Apr 07 10:29:46
2020
1459175064.0

Time date formatting symbol in Python:

  • %y Two-digit year (00-99)
  • %Y four-digit year (000-9999)
  • %m month (01-12)
  • One day in %d month (0-31)
  • %H 24 hours (0-23)
  • %I 12 hours (01-12)
  • %M minutes (00 s 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 represents
  • %j Day of the Year (001-366)
  • %p Local A.M. or P.M. equivalent
  • %U The number of 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 The number of weeks of the year (00-53) Monday is the beginning of the week
  • %x locally represented by the corresponding date
  • %X is locally represented by the appropriate time
  • The name of the current time zone for %Z
  • %% % sign itself

Get a calendar for a month

The Calendar module has a wide range of methods for working with annual and monthly calendars, such as printing monthly calendars for a month:

#!/usr/bin/python3

import calendar
cal
= calendar.month(2020, 9)
print ("以下输出2020年9月份的日历:")
print (cal)

The above example output results:

以下输出20209月份的日历:    
September 2020
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


Time module

The Time module contains the following built-in functions, both in the time-processing phase and in the conversion time format:

Serial number Functions and descriptions Instance
1 time.altzone
Returns the number of offset seconds in the daylight saving time area west of Greenwich. I f the region returns a negative value in greenwich East (e.g. Western Europe, including the United Kingdom). Enable regions for daylight saving time to use.

The following example shows how the altzone() function is used:

>>> import time
>>> print ("time.altzone %d " % time.altzone)
time.altzone -28800
2 time.asctime([tupletime])
Accept the time tudal and return a 24-character string in readable form "Tue Dec 11 18:07:14 2008" (Tuesday, December 11, 2008 18:07:14).

The following example shows how the asctime() function is used:

>>> import time
>>> t = time.localtime()
>>> print ("time.asctime(t): %s " % time.asctime(t))
time.asctime(t): Thu Apr 7 10:36:20 2016
3 time.clock()
The number of seconds calculated for floating points returns the current CPU time. It is more useful to measure the time-consuming time of different programs than time.time().
Instance
4 time.ctime([secs])
The effect is equivalent to asctime (localtime), and the failure to give parameters is equivalent to asctime()

The following example shows how the ctime() function is used:

>>> import time
>>> print ("time.ctime() : %s" % time.ctime())
time
.ctime() : Thu Apr 7 10:51:58 2016
5 time.gmtime([secs])
The receiving time drops (floating-point seconds passed after the 1970 era) and returns to the time cell t at Greenwich Astronomical Time. Note: t.tm_isdst is always 0

The following example shows how the gmtime() function is used:

>>> import time
>>> print ("gmtime :", time.gmtime(1455508609.34375))
gmtime
: time.struct_time(tm_year=2016, tm_mon=2, tm_mday=15, tm_hour=3, tm_min=56, tm_sec=49, tm_wday=0, tm_yday=46, tm_isdst=0)
6 time.localtime([secs]
The reception time drops (floating-point seconds passed after the 1970 era) and returns to the time cell t (t.tm_isdst desirable 0 or 1, depending on whether the local time is daylight saving time at that time).

The following example shows how the localtime() function is used:

>>> import time
>>>
print ("localtime(): ", time.localtime(1455508609.34375))
localtime(): time.struct_time(tm_year=2016, tm_mon=2, tm_mday=15, tm_hour=11, tm_min=56, tm_sec=49, tm_wday=0, tm_yday=46, tm_isdst=0)
7 time.mktime(tupletime)
Accept the time group and return the time drop (the floating point seconds passed after the 1970 era).
Instance
8 time.sleep(secs)
Delay the operation of the calling thread, secs refers to the number of seconds.

The following example shows how sleep() functions are used:

#!/usr/bin/python3
import
time

print
("Start : %s" % time.ctime())
time.sleep( 5 )
print
("End : %s" % time.ctime())
9 time.strftime(fmt[,tupletime])
Receives local time in time yuans and returns local time in readable strings, the format of which is determined by fmt.

The following example shows how the strftime() function is used:

>>> import time
>>> print (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
2016
-04-07 11:18:05
10 time.strptime(str,fmt='%a %b %d %H:%M:%S %Y')
Resolve a time string to a time group based on the format of fmt.

The following example shows how the strptime() function is used:

>>> import time
>>> struct_time = time.strptime("30 Nov 00", "%d %b %y")
>>> print ("返回元组: ", struct_time)
返回元组:
time.struct_time(tm_year=2000, tm_mon=11, tm_mday=30, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=335, tm_isdst=-1)
11 time.time( )
Returns the timestamp of the current time (the number of floating-point seconds passed after the 1970 era).

The following example shows how the time() function is used:

>>> import time
>>>
print(time.time())
1459999336.1963577
12 time.tzset()
Re-initialize time-related settings based on the environment variable TZ.
Instance

The Time module contains two very important properties:

Serial number Properties and descriptions
1 time.timezone
Property time.timezone is the number of offset seconds from Greenwich in the local time zone (daylight saving time is not started); most of Europe, Asia, Africa).
2 time.tzname
The property time.tzname contains a pair of strings that vary depending on the situation, named local time zone with daylight saving time, and undecided.


Calendar module

The functions of this module are calendar-related, such as printing a month's character calendar.

Monday is the default first day of the week, and Sunday is the default last day. C hanging the settings requires calling the calendar.setfirstweekday() function. The module contains the following built-in functions:

Serial number Functions and descriptions
1 calendar.calendar(year,w=2,l=1,c=6)
Returns a year calendar in the format of a multi-line string, three months and one line, at an interval of c. T he daily width interval is w character. T he length of each row is 21 x W . l is the number of rows per week.
2 calendar.firstweekday( )
Returns the settings for the current weekly start date. By default, 0 is returned the first time the calendar module is loaded, monday.
3 calendar.isleap(year)
True is returned for leap years, otherwise false.
4 calendar.leapdays(y1,y2)
Returns the total number of leap years between Y1 and Y2 years.
5 calendar.month(year,month,w=2,l=1)
Returns a multi-line string format for the year month month calendar, two lines of headings, one line a week. T he daily width interval is w character. T he length of each row is 7 x w. 6. l is the number of rows per week.
6 calendar.monthcalendar(year,month)
Returns a single-layer nested list of integers. E ach sublist mount represents an integer for a week. D ates outside the month of year are set to 0; The days in the range are expressed on the first days of the month, starting with 1.
7 calendar.monthrange(year,month)
Returns two integers. T he first is the date code for the day of the week of the month, and the second is the date code for that month. F rom 0 (Monday) to 6 (Sunday); Months from 1 to 12.
8 calendar.prcal(year,w=2,l=1,c=6)
Equivalent to print calendar.calendar (year, w, l, c).
9 calendar.prmonth(year,month,w=2,l=1)
Equivalent to print calendar.calendar (year, w, l, c).
10 calendar.setfirstweekday(weekday)
Set the start date code for each week. 0 (Monday) to 6 (Sunday).
11 calendar.timegm(tupletime)
In contrast to time.gmtime: accept a time group form that returns the time of the moment (the floating-point seconds passed after the 1970 era).
12 calendar.weekday(year,month,day)
Returns the date code for the given date. 0 (Monday) to 6 (Sunday). Months are 1 (January) to 12 (December).


Other related modules and functions

In Python, other modules that handle dates and times are: