Author: Han Xinzi@ShowMeAI
Tutorial address: http://www.showmeai.tech/tuto...
Article address: http://www.showmeai.tech/article-detail/90
Notice: All Rights Reserved. Please contact the platform and the author for reprint and indicate the source
Python date and time
In the development process of python, we often have to deal with time type data. Python has built-in standard libraries such as time and datetime to help us deal with time type. In this section, we will introduce common methods in detail around these two standard libraries.
1.time module
In Python, the time module is mainly used to convert the time stamp into a specific date and time, but the object structure of the time module is simple, which is not suitable for complex operation and representation.
(1) Module usage
There is only time in the time module struct_ Time is a class:
struct_time is a structured time object obtained by converting the number of seconds. Attributes such as year, month, day, hour, minute and second of the object can be obtained through subscript or attribute name. Call gmtime(), localtime(), strptime() and other methods to get struct_time instance.
>>> st = time.localtime() >>> st time.struct_time(tm_year=2021, tm_mon=10, tm_mday=27, tm_hour=19, tm_min=27, tm_sec=31, tm_wday=2, tm_yday=300, tm_isdst=0) >>> st.tm_mon 10 >>> st[1] 10
# In struct_ Convert between time and string >>> time.strftime('%H:%M:%S') '19:10:37' >>> time.strptime("30 Nov 00", "%d %b %y") 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)
import time # Formatted as 2021-10-27 19:56:36 print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) # Formatted as Sat Mar 28 22:24:24 2016 print(time.strftime("%a %b %d %H:%M:%S %Y", time.localtime())) # Convert format string to timestamp a = "Wed Oct 27 19:56:36 2021" print(time.mktime(time.strptime(a,"%a %b %d %H:%M:%S %Y")))
2.datetime module
The datetime module supports the operation of date and time. It provides some classes for operating date and time. Most of the functions of the module are implemented around the methods and properties of the following four classes (and the other two classes about time zone).
(1) date class and usage
The date class represents the date type.
Supported operators:
- It supports comparison operations with another date object, such as = =, ≤, <, ≥, >.
- It supports addition and subtraction with timedelta object, and the result is still date object.
- Support subtraction with another date object to get the timedelta object.
- Hash is supported.
Code example:
# Pass in the year, month and day parameter corresponding to the date, and instantiate the date class >>> from datetime import date >>> date(2021, 10, 29) datetime.date(2021, 10, 29) # Time can be obtained by timestamp >>> date.fromtimestamp(time.time()) datetime.date(2021, 10, 29) >>> d2 = date(2021, 10, 29) >>> d1 = date(2021, 10, 27) >>> d2 > d1 True >>> d2 - d1 datetime.timedelta(days=2)
(2) time class and usage
The time class represents the type of time (hour, minute, second).
Supported operators
- It supports comparison operations with another time object, such as = =, ≤, <, ≥, >.
- Hash is supported.
Code example
>>> from datetime import time >>> t = time.fromisoformat('19:32:10') >>> t.strftime('%Hh %Mm %Ss') '19h 32m 10s' >>> t = time(hour=19, minute=27, second=55) >>> t.isoformat() '19:27:55'
(3) datetime class and usage
datetime class represents the time type including date and time, which can be regarded as a combination of date and time instances. Therefore, it has most of the methods and properties of the two objects at the same time.
Supported operators
- Datetime supports equal comparison with date, but the resu lt must be False. In addition, only comparison operations such as = =, ≤, <, ≥, > with another datetime object are supported.
- It supports adding with timedelta, and the result is datetime; It supports addition and subtraction with timedelta object. The result is still datetime object. Subtract with another datetime object to get timedelta object.
- Hash is also supported.
Code example
>>> from datetime import datetime >>> datetime(year=2021, month=10, day=29) datetime.datetime(2021, 10, 29, 0, 0) >>> datetime.now() datetime.datetime(2021, 10, 29, 14, 51, 18, 731235) >>> datetime.fromisoformat('2021-10-29 16:09:32') datetime.datetime(2021, 10, 29, 16, 9, 32) >>> dt = datetime.now() >>> dt.timestamp() 1635317544.682565 >>> dt.date() datetime.date(2021, 10, 29)
(4)timedelta
The timedelta class object represents the difference between two datetime objects.
Supported operators
- It only supports the comparison with another timede lt a, such as = =, ≤, <, ≥, >.
- The timedelta object supports addition and subtraction. Adding or subtracting datetime and timedelta still returns datetime.
- timedelta also supports multiplication, division, modulo division and other operators.
- Hash is supported.
- timedelta is signed and supports abs() function, which can return the absolute interval between two datetime s.
Code example
>>> from datetime import timedelta >>> timedelta(days=2) datetime.timedelta(days=2) >>> dt1 = datetime.now() >>> dt2 = datetime.now() >>> dt2 -dt1 datetime.timedelta(seconds=4, microseconds=476390) >>> d = timedelta(minutes=3, seconds=35) >>> d.total_seconds() 215.0
Data and code download
The code for this tutorial series can be found in github corresponding to ShowMeAI Download in, you can run in the local python environment. Babies who can surf the Internet scientifically can also directly use Google lab to run and learn through interactive operation!
The Python quick look-up table involved in this tutorial series can be downloaded and obtained at the following address:
Extended references
ShowMeAI related articles recommended
- Introduction to python
- python installation and environment configuration
- python basic syntax
- python basic data type
- python operator
- python conditional control and if statement
- python loop statement
- python while loop
- python for loop
- python break statement
- python continue statement
- python pass statement
- python string and operation
- python list
- python tuple
- python dictionary
- python collection
- python function
- python iterators and generators
- python data structure
- python module
- python file reading and writing
- python file and directory operation
- python error and exception handling
- python object oriented programming
- python namespace and scope
- python time and date
ShowMeAI series tutorial recommendations
- Illustrated Python Programming: a series of tutorials from getting started to mastering
- Graphic data analysis: a series of tutorials from introduction to mastery
- Fundamentals of graphic AI Mathematics: a series of tutorials from introduction to mastery
- Illustrated big data technology: a series of tutorials from introduction to mastery