Fundamentals of python (8): time related modules

Python sophomore 2021-07-25 02:03:22
fundamentals python time related modules


 

watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=

1 time modular

time The module provides many time-related classes and functions , Let's introduce some common .

1.1 struct_time class

time Modular struct_time Class represents a time object , You can access values through indexes and property names . The corresponding relationship is as follows :

Indexes attribute value
0 tm_year( year ) Such as :1945
1 tm_mon( month ) 1 ~ 12
2 tm_mday( Japan ) 1 ~ 31
3 tm_hour( when ) 0 ~ 23
4 tm_min( branch ) 0 ~ 59
5 tm_sec( second ) 0 ~ 61
6 tm_wday( Zhou ) 0 ~ 6
7 tm_yday( What day of the year ) 1 ~ 366
8 tm_isdst( Summer season ) -1、0、1

tm_sec The scope is 0 ~ 61, value 60 Indicates that it is valid in the timestamp of leap seconds , And the value is supported for historical reasons 61.

localtime() Indicates the current time , The return type is struct_time object , An example is shown below :

  •  
import timet = time.localtime()print('t-->', t)print('tm_year-->', t.tm_year)print('tm_year-->', t[0])

Output results :

  •  
t--> time.struct_time(tm_year=2019, tm_mon=12, tm_mday=1, tm_hour=19, tm_min=49, tm_sec=54, tm_wday=6, tm_yday=335, tm_isdst=0)tm_year--> 2019tm_year--> 2019

1.2 Common functions

function ( Constant ) explain
time() Returns the timestamp of the current time
gmtime([secs]) Convert timestamp to Greenwich astronomical time struct_time, Optional parameters secs From epoch The number of seconds to now , The default is the current time
localtime([secs]) And gmtime() be similar , Return to... At local time struct_time
mktime(t) localtime() The inverse function of
asctime([t]) Receive one struct_time Time represented , The return form is :Mon Dec  2 08:53:47 2019 String
ctime([secs]) ctime(secs) amount to asctime(localtime(secs))
strftime(format[, t]) Format date , Receive one struct_time Time represented , And returns the local time in a readable string
sleep(secs) Pauses execution for the number of seconds specified by the calling thread
altzone Local DST Time zone offset , With UTC In seconds
timezone Local ( Not DST) Time zone offset ,UTC Seconds to the West ( Most of Western Europe is negative , The United States is positive , Britain is zero )
tzname Tuples of two strings : The first is local non DST The name of the time zone , The second is local DST The name of the time zone

epoch:1970-01-01 00:00:00 UTC

The basic usage is as follows :

  •  
import time
print(time.time())print(time.gmtime())print(time.localtime())print(time.asctime(time.localtime()))print(time.tzname)# strftime Use print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()))

strftime The function date formatting symbol is described as follows :

Symbol explain
%a Localized abbreviation for the name of the day of the week
%A Full name of the day of the week in localization
%b Localized month abbreviation name
%B Localized month full name
%c The appropriate date and time representation for localization
%d Decimal number [01,31] Indicates the day of the month
%H Decimal number [00,23] Hours represented (24 hourly )
%I Decimal number [01,12] Hours represented (12 hourly )
%j Decimal number [001,366] It means mid year day
%m Decimal number [01,12] Indicates the month
%M Decimal number [00,59] Indicates the minutes of the
%p Localized AM or PM
%S Decimal number [00,61] Represents the seconds
%U Decimal number [00,53] The number of weeks in a year ( Sunday is the first day of the week )
%w Decimal number [0( Sunday ),6] The day of the week
%W Decimal number [00,53] The number of weeks in a year ( Monday as the first day of the week )
%x The appropriate date for localization means
%X Appropriate time representation of localization
%y Decimal number [00,99] Indicates a year without a century
%Y A year with a century represented by a decimal number
%z The time zone offset is in the format +HHMM or -HHMM Formal UTC/GMT Positive or negative TDOA indication of , among H Represents a decimal hour number ,M Represents a decimal minute number [-23:59, +23:59]
%Z Time zone name
%% Literally '%' character

2 datetime modular

datatime The module is repackaged time modular , Provides more interfaces , Become more intuitive and easy to call .

2.1 date class

date Class represents a by year 、 month 、 Date of day composition , The format is :datetime.date(year, month, day).

  • year The scope is :[1, 9999]

  • month The scope is :[1, 12]

  • day The scope is [1, The number of days corresponding to a given year ].

Class methods and properties are as follows :

Method ( attribute ) explain
today() Returns the current local date
fromtimestamp(timestamp) Kill according to the given time , Return local date
min date The minimum date that can be represented
max date The maximum date that can be represented

Examples of use are as follows :

  •  
import datetimeimport time
print(datetime.date.today())print(datetime.date.fromtimestamp(time.time()))print(datetime.date.min)print(datetime.date.max)

The instance methods and properties are as follows :

Method ( attribute ) explain
replace(year, month, day) Generate a new date object , The year specified by the parameter , month , The day replaces the attribute in the original object
timetuple() Return the date corresponding to struct_time object
weekday() Returns an integer representing the day of the week , Monday is 0, Sunday is 6
isoweekday() Returns an integer representing the day of the week , Monday is 1, Sunday is 7
isocalendar() The return format is (year,month,day) tuples
isoformat() The return format is as follows YYYY-MM-DD String
strftime(format) Returns a custom formatted string
year year
month month
day Japan

Examples of use are as follows :

  •  
import datetime
td = datetime.date.today()print(td.replace(year=1945, month=8, day=15))print(td.timetuple())print(td.weekday())print(td.isoweekday())print(td.isocalendar())print(td.isoformat())print(td.strftime('%Y %m %d %H:%M:%S %f'))print(td.year)print(td.month)print(td.day)

2.2 time class

time Class is represented by 、 branch 、 second 、 Time in microseconds , The format is :time(hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0).

  • hour The scope is :[0, 24)

  • minute The scope is :[0, 60)

  • second The scope is :[0, 60)

  • microsecond The scope is :[0, 1000000)

  • fold The scope is :[0, 1]

The instance methods and properties are as follows :

Method ( attribute ) explain
isoformat() return HH:MM:SS Format string
replace(hour, minute, second, microsecond, tzinfo, * fold=0) Create a new time object , When specified with a parameter 、 branch 、 second 、 Microseconds replace the properties in the original object
strftime(format) Returns a custom formatted string
hour when
minute branch
second second
microsecond Microsecond
tzinfo The time zone

Examples of use are as follows :

  •  
import datetime
t = datetime.time(10, 10, 10)print(t.isoformat())print(t.replace(hour=9, minute=9))print(t.strftime('%I:%M:%S %p'))print(t.hour)print(t.minute)print(t.second)print(t.microsecond)print(t.tzinfo)

2.3 datetime class

datetime It includes date And time All the information about , The format is :datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0), Parameter range value reference date Class and time class .

Class methods and properties are as follows :

Method ( attribute ) explain
today() Return to the current local time
now(tz=None) Be similar to today(), Optional parameters tz Time zone can be specified
utcnow() Returns the current UTC Time
fromtimestamp(timestamp, tz=None) Return the corresponding time according to the timestamp
utcfromtimestamp(timestamp) Return the corresponding... According to the timestamp UTC Time
combine(date, time) according to date and time Return the corresponding time
min datetime The minimum date that can be represented
max datetime The maximum date that can be represented

Examples of use are as follows :

  •  
import datetime
print(datetime.datetime.today())print(datetime.datetime.now())print(datetime.datetime.utcnow())print(datetime.datetime.fromtimestamp(time.time()))print(datetime.datetime.utcfromtimestamp(time.time()))print(datetime.datetime.combine(datetime.date(2019, 12, 1), datetime.time(10, 10, 10)))print(datetime.datetime.min)print(datetime.datetime.max)

The instance methods and properties are as follows :

Method ( attribute ) explain
date() Return with the same year,month,day It's worth it date object
time() Return with the same hour, minute, second, microsecond and fold It's worth it time object
replace(year, month, day=self.day, hour, minute, second, microsecond, tzinfo, * fold=0) Generate a new date object , The year specified by the parameter , month , Japan , when , branch , second ... Replace the properties in the original object
weekday() Returns an integer representing the day of the week , Monday is 0, Sunday is 6
isoweekday() Returns an integer representing the day of the week , Monday is 1, Sunday is 7
isocalendar() The return format is (year,month,day) tuples
isoformat() Return one to ISO 8601 Format string representing date and time YYYY-MM-DDTHH:MM:SS.ffffff
strftime(format) Returns a custom formatted string
year year
month month
day Japan
hour when
minute branch
second second
microsecond Microsecond
tzinfo The time zone

Examples of use are as follows :

  •  
import datetime
td = datetime.datetime.today()print(td.date())print(td.time())print(td.replace(day=11, second=10))print(td.weekday())print(td.isoweekday())print(td.isocalendar())print(td.isoformat())print(td.strftime('%Y-%m-%d %H:%M:%S .%f'))print(td.year)print(td.month)print(td.month)print(td.hour)print(td.minute)print(td.second)print(td.microsecond)print(td.tzinfo)

3 calendar modular

calendar The module provides many functions that can handle calendars .

3.1 Common functions

Method explain
setfirstweekday(weekday) Set the beginning of each week (0 For Monday ,6 Sunday )
firstweekday() Returns the value of the first day of each week currently set
isleap(year) If year If it's a leap year, return to True , Otherwise return to False
leapdays(y1, y2) return y1 to y2 ( contain y1 and y2 ) The number of leap years between
weekday(year, month, day) Returns the week value of the specified date
monthrange(year, month) Returns the day of the week and the number of days of the month on the first day of the specified month in the specified year
month(theyear, themonth, w=0, l=0) Return to month calendar
prcal(year, w=0, l=0, c=6, m=3) Return year calendar

Examples of use are as follows :

  •  
import calendar
calendar.setfirstweekday(1)print(calendar.firstweekday())print(calendar.isleap(2019))print(calendar.leapdays(1945, 2019))print(calendar.weekday(2019, 12, 1))print(calendar.monthrange(2019, 12))print(calendar.month(2019, 12))print(calendar.prcal(2019))

3.2 Calendar class

Calendar Object provides some methods for formatting calendar data , The example method is as follows :

Method explain
iterweekdays() Returns an iterator , The content of the iterator is the number of a week
itermonthdates(year, month) Returns an iterator , The content of the iterator is year 、 The date of the month

Examples of use are as follows :

  •  
from calendar import Calendar
c = Calendar()print(list(c.iterweekdays()))for i in c.itermonthdates(2019, 12): print(i)

3.3 TextCalendar class

TextCalendar by Calendar Subclass , Used to generate a plain text calendar . The example method is as follows :

Method explain
formatmonth(theyear, themonth, w=0, l=0) Returns a multiline string representing the specified year 、 The calendar of the month
formatyear(theyear, w=2, l=1, c=6, m=3) Return to one m Column calendar , Optional parameters w, l, and c Respectively represents the number of date columns , Number of rows per week , The interval between and months

Examples of use are as follows :

  •  
from calendar import TextCalendar
tc = TextCalendar()print(tc.formatmonth(2019, 12))print(tc.formatyear(2019))

3.4 HTMLCalendar class

HTMLCalendar Class can generate HTML The calendar . The example method is as follows :

Method explain
formatmonth(theyear, themonth, withyear=True) Return to one HTML Form as specified year 、 The calendar of the month
formatyear(theyear, width=3) Return to one HTML Table as calendar for the specified year
formatyearpage(theyear, width=3, css='calendar.css', encoding=None) Return a complete HTML Page as calendar for the specified year

Examples of use are as follows :

  •  
from calendar import HTMLCalendar
hc = HTMLCalendar()print(hc.formatmonth(2019, 12))print(hc.formatyear(2019))print(hc.formatyearpage(2019))

watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=

版权声明
本文为[Python sophomore]所创,转载请带上原文链接,感谢
https://pythonmana.com/2021/06/20210628151507153I.html

  1. 小白量化投资交易入门课(python入门金融分析)
  2. Python:PyCharm选择性忽略PEP8警告
  3. Python: pychar selectively ignores pep8 warnings
  4. Django-模板
  5. Django template
  6. Python正则表达式大全
  7. 最全Python正则表达式来袭
  8. A python knowledge for Xiaobai
  9. 2. Flexible pandas index
  10. 1. Get to know pandas
  11. See how I use Python to create a magic with baby (one play can play for a day)?
  12. Wow, python can do real-time translation
  13. Python经典编程习题100例
  14. 100 examples of Python classic programming exercises
  15. Invincible, with Python for English teachers to develop a magic tool for English composition correction (support primary school to IELTS)
  16. 抖音数据采集教程,最全python库selenium自动化使用
  17. Pandas 11-综合练习
  18. Pandas 11 - comprehensive exercises
  19. Pandas基础|用户游览日志时间合并排序
  20. python自学 第三章 python语言基础之保留字、标识符与内置函数
  21. python学习例程3-函数
  22. Python GUI 之Tkinter小结 - 知乎
  23. Pandas foundation | user travel log time merge sort
  24. Chapter 3 reserved words, identifiers and built-in functions of the foundation of Python
  25. Tkinter summary of Python GUI - Zhihu
  26. 【Python常用包】itertools
  27. Itertools
  28. [Python] Matplotlib 图表的绘制和美化技巧
  29. Drawing and beautifying skills of [Python] Matplotlib chart
  30. Drawing and beautifying skills of [Python] Matplotlib chart
  31. Python序列之列表(一)
  32. Python解析库lxml与xpath用法总结
  33. Python解析库lxml与xpath用法总结
  34. Usage Summary of Python parsing library lxml and XPath
  35. Usage Summary of Python parsing library lxml and XPath
  36. Python web/HTML GUI
  37. Why is sanic better than Django flame?
  38. Wechat applet Python sends subscription message
  39. Invincible, with Python for English teachers to develop an English composition correction artifact (support primary school to IELTS)
  40. How can I use Python to create a magic with children (one can play for one day)?
  41. Pandas module
  42. Machine learning in Python - Boston house price forecast
  43. 50 Great Python modules
  44. Share the survival status of Python practitioners and tell you the real salary of general programmers
  45. Pandas basic operation update
  46. Python Programming day02 Python operator
  47. Usage Summary of Python parsing library lxml and XPath
  48. 1. First meeting pandas
  49. Conversion between Python and base conversion between Python and base
  50. Basics of Python
  51. Fundamentals of python (XIV): errors and exceptions
  52. Fundamentals of python (I): necessary knowledge for getting started
  53. Operators in Python 3
  54. The list of national computer non graduate schools (captured by Python), just look at this one!
  55. Python data visualization: Seaborn
  56. Quick start pandas (lower)
  57. Operators in Python 3
  58. Python tarfile module
  59. Python basic syntax