Introduction and use of the datetime module in python - used to process date and time, calculate time intervals, etc.

Table of contents

1. Summary of the five major categories of datetime modules:

2. Introduction and practice of classes in datetime module

2.1, date class

2.1.1. Construction methods and examples

2.1.2 Class methods

2.2, time class

2.2.1. time data structure

2.2.2. Class methods and properties 

 2.3, datetime class

2.3.1. Data composition of datetime class

2.3.2. Class methods

2.4, timedelta class

2.4.1. timedelta attribute

2.4.2. Use

3. Appendix: Time and date formatting symbols in python


1. Summary of the five major categories of datetime modules:

kind effect
datetime.date Class representing date, mainly used to handle year, month, day
datetime.time Class representing time, mainly used to handle hours, minutes and seconds
datetime.datetime Class representing date and time. The comprehensive use of date class and time class can handle year, month, day, hour, minute and second.
datetime.timedelta Represents the time interval, that is, the interval between two time points, mainly used for time addition and subtraction.
datetime.tzinfo Information about time zones

Datetime is commonly used in python. It is mainly used to deal with time and date. It is a very useful module. When dealing with programming problems and practical applications of time and date calculations, it can be applied directly. When using the following classes, you must first import datetime.

2. Introduction and practice of classes in datetime module

2.1, date class

The date class contains three parameters, namely year, month, and day, and the return format is year-month-day.

2.1.1. Construction methods and examples

1) today(): Construct an object using today's date , which can be accessed through yearmonthdaythree data descriptors,

You can also use date() to construct a desired date yourself instead of using today().

Examples are as follows:

Source code, can be copied and pasted

import datetime
a = datetime.date.today()
b = datetime.date(2000, 12, 29)

2.1.2 Class methods

1) Two methods for querying the day of the week isoweekday(): Return the number of the week that complies with the ISO standard for the specified date (Monday is 1...Sunday is 7). weekday(...)The method returns Monday as 0 and Sunday as 6.

Examples are as follows:

2)  : This method returns an array of type timetuple(...)for compatibility , but some element values ​​related to time are 0time.localtime(...)time.struct_time

Examples are as follows:

 3) isocalendar(): Returns a tuple containing three values, the three values ​​are: yearyear, week numberweek number, weekdayweek number (Monday is 1...Sunday is 7): 

An example is as follows: Monday of the 12th week of 2023

 4) isoformat(): returns standard date format

An example is as follows: YYYY-MM-DD

5) Compare date size

The return value of the method is True\False

 

 Examples are as follows:

6) Get the number of days difference between two dates

 Usage __sub__()and __rsub__()method, in fact, the two methods are not much different, one is forward operation and the other is reverse operation.

 An example is as follows: The return value type of the calculation result isdatetime.timedelta 

If you want to get an integer type result, do the following: 

2.2. Time class:

2.2.1. time data structure

timeThe class consists of hourhours, minuteminutes, secondseconds, microsecondmilliseconds and tzinfofive parts,

 Examples are as follows:

2.2.2. Class methods and properties 

1) Compare time size: dateThe usage method is the same as the method defined in the class, so I won’t introduce it in detail here.

Examples are as follows:

 2) Output time: If you want the output time characters to comply with the ISO standard, please use isoformat(),a string that simply obtains the time, then use__str__()

示例如下:

If you want to convert a time object into a string object, you can use __format__()the method to output the time in a specified format. The equivalent method to this method isstrftime() 

 2.3, datetime class

2.3.1. Data composition of datetime class

1)datetimeIn fact, a class can be regarded as a combination of dateclass and timeclass. Most of its methods and attributes are inherited from these two classes. For related operation methods, please refer to the introduction of the two classes above in this article. Its data structure is also composed of all the attributes of these two classes.

 datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]])

2.3.2. Class methods

1) now(): returns the datetime object of the current date and time, date(), returns the date part of the datetime object, time() returns the time part of the datetime object, utctimetuple(): returns the UTC time tuple, utcnow(...): Returns a UTC datetime object for the current datetime:

Examples are as follows:

2) combine(): combine a date object and a time object to generate a datetime object

Examples are as follows:

 3) strptime(): Returns a corresponding datetime object based on the two parameters string and format. 

Examples are as follows:

2.4, timedelta class

2.4.1. timedelta attribute

It is used to calculate the difference between two datetimeobjects. 
This class contains the following attributes: 
1. days:number of days 
2、microseconds: number of microseconds (>=0 and <1 second) 
3. seconds:number of seconds (>=0 and <1 day)

2.4.2. Use

Examples are as follows:

Get the date of the last day of the previous month

 Get time difference

Calculate the time 892612 seconds backward from the current time 

2.4.3. Example questions (Source: Lanqiao Cup)

It may seem complicated, but in fact it just requires a lot of explanation, and it can be easily completed using the knowledge explained in this article.

Answer source code:

https://github.com/yanhanrebecca/python_test_project/blob/master/Algorithmic_practice/datetime_test.py

3. Appendix: Time and date formatting symbols in python

Guess you like

Origin blog.csdn.net/weixin_45440484/article/details/129660039