[Python] Python Advanced Series Tutorials--Python3 Date and Time (10)

foreword

Past review:

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

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

The time interval is a floating point fraction of seconds.

Each timestamp is expressed in terms of how much time has elapsed since midnight, January 1, 1970 (epoch).

Python's time module has many functions to convert common date formats. For example, the function time.time() is used to obtain the current timestamp, as shown in the following example:

example

#!/usr/bin/python3

import time  # 引入time模块

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

The output of the above example:

当前时间戳为: 1459996086.7115328

Timestamp units are best suited for date arithmetic. But dates before 1970 cannot be expressed in this way. Dates that are too far out won't work either, UNIX and Windows are only supported until 2038.

What is a time tuple?

Many Python functions process time with groups of 9 numbers assembled by an element:

serial number field value
0 4 digit year 2008
1 moon 1 to 12
2 Day 1 to 31
3 Hour 0 to 23
4 minute 0 to 59
5 Second 0 to 61 (60 or 61 is a leap second)
6 day of the week 0 to 6 (0 is Monday)
7 what day of the year 1 to 366 (Julian calendar)
8 summer time -1, 0, 1, -1 is the flag to determine whether it is daylight saving time

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

serial number field 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
6 tm_wday 0 to 6 (0 is Monday)
7 tm_yday 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

get current time

To convert from a timestamp that returns a float to a time tuple, just pass the float to a function such as localtime.

#!/usr/bin/python3

import time

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

The output of the above example:

本地时间为 : 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)

Get formatted time

You can choose any format according to your needs, but the easiest function to get a human-readable time pattern is asctime():

#!/usr/bin/python3

import time

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

The output of the above example:

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

format date

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

time.strftime(format[, t])

example

#!/usr/bin/python3

import time

# 格式化成2016-03-20 11:45:39形式
print (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))

# 格式化成Sat Mar 28 22:24:24 2016形式
print (time.strftime("%a %b %d %H:%M:%S %Y", time.localtime()))
 
# 将格式字符串转换为时间戳
a = "Sat Mar 28 22:24:24 2016"
print (time.mktime(time.strptime(a,"%a %b %d %H:%M:%S %Y")))

The output of the above example:

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

Time and date formatting symbols in python:

  • %y two-digit year representation (00-99)
  • %Y four-digit year representation (000-9999)
  • %m month (01-12)
  • %d day of month (0-31)
  • %H Hours in 24-hour format (0-23)
  • %I Hours in 12-hour format (01-12)
  • %M minutes (00=59)
  • %S seconds (00-59)
  • %a local abbreviated weekday name
  • %A local full weekday name
  • %b local abbreviated month name
  • %B local full month name
  • %c local corresponding date representation and time representation
  • %j day of the year (001-366)
  • %p equivalent of local AM or PM
  • %U week number of the year (00-53) Sunday is the beginning of the week
  • %w week (0-6), Sunday is the beginning of the week
  • %W week number of the year (00-53) Monday is the beginning of the week
  • %x local corresponding date representation
  • %X local corresponding time representation
  • %Z the name of the current time zone
  • %% % sign itself

Get a month calendar

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

example

#!/usr/bin/python3

import calendar

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

The output of the above example:

以下输出20161月份的日历:
    January 2016
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 for time manipulation and for converting time formats:

serial number function and description example
1 time.altzone
returns the offset in seconds for the daylight saving time zone west of Greenwich. Negative values ​​are returned if the region is east of Greenwich (eg Western Europe, including the UK). To be used in regions where Daylight Saving Time is enabled.
The following example shows how to use the altzone() function:
>>> import time
>>> print ("time.altzone %d " % time.altzone)
time.altzone -28800
2 time.asctime([tupletime])
takes a time tuple and returns a 24-character readable form of "Tue Dec 11 18:07:14 2008" String.
The following example shows how to use the asctime() function:
>>> 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()
returns the current CPU time in seconds as a floating point number. Used to measure the time-consuming of different programs, more useful than time.time().
Example
Because this method depends on the operating system, it is not recommended after Python 3.3, but it is removed in version 3.8, and the following two functions need to be used instead.
time.perf_counter() # Return system running time
time.process_time() # Return process running time
4 time.ctime([secs])
is equivalent to asctime(localtime(secs)), if no parameter is given, it is equivalent to asctime()
The following example shows how to use the ctime() function:
>>> import time
>>> print (“time.ctime() : %s” % time.ctime())time.ctime() : Thu Apr 7 10: 51:58 2016
5 time.gmtime ([secs])
takes a timestamp (float seconds elapsed since the 1970 epoch) and returns a time tuple t in Greenwich Mean Time. Note: t.tm_isdst is always 0
The following example shows how to use the gmtime() function:
>>> 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]
接收时间戳(1970纪元后经过的浮点秒数)并返回当地时间下的时间元组t(t.tm_isdst可取0或1,取决于当地当时是不是夏令时)。
以下实例展示了 localtime()函数的使用方法:
>>> 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)
接受时间元组并返回时间戳(1970纪元后经过的浮点秒数)。
8 time.sleep(secs)
推迟调用线程的运行,secs指秒数。
以下实例展示了 sleep()函数的使用方法:
#!/usr/bin/python3
import time
print (“Start : %s” % time.ctime())
time.sleep( 5 )
print (“End : %s” % time.ctime())
9 time.strftime(fmt[,tupletime])
接收以时间元组,并返回以可读字符串表示的当地时间,格式由fmt决定。
以下实例展示了 strftime()函数的使用方法:
>>> 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’)
根据fmt的格式把一个时间字符串解析为时间元组。
以下实例展示了 strptime()函数的使用方法:
>>> 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( )
返回当前时间的时间戳(1970纪元后经过的浮点秒数)。
以下实例展示了 time()函数的使用方法:
>>> import time
>>> print(time.time())1459999336.1963577
12 time.tzset()
根据环境变量TZ重新初始化时间相关设置。
-
13 time.perf_counter()
返回计时器的精准时间(系统的运行时间),包含整个系统的睡眠时间。由于返回值的基准点是未定义的,所以,只有连续调用的结果之间的差才是有效的。
-
14 time.process_time()
返回当前进程执行 CPU 的时间总和,不包含睡眠时间。由于返回值的基准点是未定义的,所以,只有连续调用的结果之间的差才是有效的。
-

Time模块包含了以下2个非常重要的属性:

序号 属性及描述
1 time.timezone
属性time.timezone是当地时区(未启动夏令时)距离格林威治的偏移秒数(>0,美洲;<=0大部分欧洲,亚洲,非洲)。
2 time.tzname
属性time.tzname包含一对根据情况的不同而不同的字符串,分别是带夏令时的本地时区名称,和不带的。

日历(Calendar)模块

此模块的函数都是日历相关的,例如打印某月的字符月历。

星期一是默认的每周第一天,星期天是默认的最后一天。更改设置需调用calendar.setfirstweekday()函数。模块包含了以下内置函数:

序号 属性及描述
1 calendar.calendar(year,w=2,l=1,c=6)
返回一个多行字符串格式的 year 年年历,3 个月一行,间隔距离为 c。 每日宽度间隔为w字符。每行长度为 21* W+18+2* C。l 是每星期行数。
2 calendar.firstweekday( )
返回当前每周起始日期的设置。默认情况下,首次载入 calendar 模块时返回 0,即星期一。
3 calendar.isleap(year)
是闰年返回 True,否则为 False。
>>> import calendar
>>>print(calendar.isleap(2000))
True
>>> print(calendar.isleap(1900))
False
4 calendar.leapdays(y1,y2)
返回在Y1,Y2两年之间的闰年总数。
5 calendar.month(year,month,w=2,l=1)
返回一个多行字符串格式的year年month月日历,两行标题,一周一行。每日宽度间隔为w字符。每行的长度为7* w+6。l是每星期的行数。
6 calendar.monthcalendar(year,month)
返回一个整数的单层嵌套列表。每个子列表装载代表一个星期的整数。Year年month月外的日期都设为0;范围内的日子都由该月第几日表示,从1开始。
7 calendar.monthrange(year,month)
返回两个整数。第一个是该月的星期几,第二个是该月有几天。星期几是从0(星期一)到 6(星期日)。
>>> import calendar
>>> calendar.monthrange(2014, 11)
(5, 30)
(5, 30)解释:5 表示 2014 年 11 月份的第一天是周六,30 表示 2014 年 11 月份总共有 30 天。
8 calendar.prcal(year, w=0, l=0, c=6, m=3)
相当于 print (calendar.calendar(year, w=0, l=0, c=6, m=3))。
9 calendar.prmonth(theyear, themonth, w=0, l=0)
相当于 print(calendar.month(theyear, themonth, w=0, l=0))。
10 calendar.setfirstweekday(weekday)
设置每周的起始日期码。0(星期一)到6(星期日)。
11 calendar.timegm(tupletime)
和time.gmtime相反:接受一个时间元组形式,返回该时刻的时间戳(1970纪元后经过的浮点秒数)。
12 calendar.weekday(year,month,day)
返回给定日期的日期码。0(星期一)到6(星期日)。月份为 1(一月) 到 12(12月)。

其他相关模块和函数

在Python中,其他处理日期和时间的模块还有:

time 模块
datetime模块

Guess you like

Origin blog.csdn.net/u011397981/article/details/131149771