Python date and time processing module (date and datetime)
高洛峰
Release: 2017-02-20 10:10:58
Original
1441 people have browsed it
Preface
In development work, we often need to use date and time, such as:
as log information The content output
Calculate the execution time of a certain function
Name the name of a log file with date
Record or display the publishing or modification time of an article
Others
Python provides multiple functions for date and Built-in modules for time operations: time module, datetime module and calendar module. The time module is implemented by calling the C library, so some methods may not be called on some platforms, but most of the interfaces it provides are basically consistent with the C standard library time.h. Compared with the time module, the interface provided by the datetime module is more intuitive, easier to use, and more powerful.
1. Explanation of related terms
UTC time Coordinated Universal Time, also known as Greenwich Astronomy Time, Universal Time. Corresponding to UTC time is the local time of each time zone. The time in East N zone is N hours earlier than UTC time, so UTC time + N hours is the local time of East N zone; while the time in West N zone is N hours later than UTC time. hours, that is, UTC time - N hours is the local time in West N zone; China is in East 8 zone, so it is 8 hours earlier than UTC time and can be expressed as UTC+8.
epoch time represents the starting point of the beginning of time; it is a specific time, and the value of this time point is different on different platforms. For Unix, epoch time is 1970-01 -01 00:00:00 UTC.
timestamp (timestamp) Also known as Unix time or POSIX time; it is a time representation that represents 0:00:00 on January 1, 1970 GMT The number of milliseconds that have elapsed since the beginning. Its value is of type float. However, the related methods of some programming languages return the number of seconds (this is the case with Python). This requires reading the documentation of the method. It should be noted that the timestamp is a difference value, and its value has nothing to do with the time zone.
2. The expression form of time
The common time expression form is:
Time stamp
Formatted time string
There are other time representations in Python:
Time.struct_time of the time module
The datetime class of the datetime module
About the datetime class of the datetime module It will be explained in detail below, but here we will briefly talk about time.struct_time.
time.struct_time contains the following attributes:
##Subscript/Index
Attribute name
Description
##0
tm_year
Year, such as 2017
1
tm_mon
Month, the value range is [1, 12]
2
tm_mday
The day of the month, the value range is [1-31]
##3
tm_hour
hours, the value range is [0-23]
4
tm_min
minutes, the value range is [0, 59]
5
tm_sec
seconds, the value range is [0, 61]
6
tm_wday
The day of the week, the value range is [0-6], 0 means Monday
7
tm_yday
The day of the year, the value range is [1, 366]
##8
tm_isdst
Whether it is daylight saving time, the possible values are: 0, 1 or -1
There are two ways to obtain attribute values:
You can think of it as a special ordered immutable sequence to obtain the value of each element through subscript/index, such as t [0]
You can also get the value of each element through the .attribute name, such as t.tm_year.
It should be noted that each attribute of the struct_time instance is read-only and cannot be modified.
3. Time module
The time module is mainly used for time access and conversion. This module provides various time-related functions.
1. Function list
##Method/Property
Description
time.altzone
Returns the time difference from UTC time in seconds (the value is positive in the west zone and positive in the east zone) value is negative). It represents the offset of the local DST time zone and is only used when daylight is non-0.
time.clock()
Returns the number of processor running time seconds consumed by the current process (excluding sleep time), the value is a decimal; this method Python3. 3 was changed to time.process_time()
time.asctime([t])
Convert a time in the form of tuple or struct_time (can be passed through gmtime() and (obtained by the localtime() method) and converted into a 24-character time string in the format: "Fri Aug 19 11:14:16 2016". If parameter t is not provided, the return value of localtime() is taken as the parameter.
time.ctime([secs])
The function is the same as above, converting the time represented by a seconds timestamp into a string representing the current local time. If the parameter secs is not provided or the value is None, the return value of the time() method is used as the default value. ctime(secs) is equivalent to asctime(localtime(secs))
time.time()
Returns the timestamp (since 1970-1-1 0:00 :00 The number of seconds elapsed so far)
time.localtime([secs])
Returns a struct_time object corresponding to the local time corresponding to the specified timestamp (can be passed Subscript, you can also refer to internal properties by .property name) format
time.localtime(time.time() + n*3600)
Return The struct_time object format of the local time n hours later (can be used to implement functions similar to crontab)
time.gmtime([secs])
Returns the specified timestamp The corresponding struct_time object format of the utc time (8 hours different from the current local time)
time.gmtime(time.time() + n*3600)
Return The struct_time object of UTC time n hours later (internal attributes can be referenced by .attribute name) format
time.strptime(time_str, time_format_str)
will The time string is converted into a struct_time time object, such as: time.strptime('2017-01-13 17:07', '%Y-%m-%d %H:%M')
time.mktime(struct_time_instance)
Convert struct_time object instance into timestamp
Time and string format in timestamp format Although the time can be converted through the ctime([secs]) method, the string format is not suitable for China's national conditions. Therefore, on the whole, they cannot be converted directly and need to use struct_time as an intermediary. The conversion relationship is as follows:
Explanation: The above '%H:%M:%S ' can be directly replaced by '%X'.
4. Datetime module
The datetime module provides classes for processing dates and times, both in simple ways and in complex ways. . Although it supports date and time algorithms, the focus of its implementation is to provide efficient attribute extraction functions for output formatting and operations.
1. Classes defined in the datetime module
The datetime module defines the following classes:
Class name
Description
##datetime.date
represents date, commonly used Attributes include: year, month and day
##datetime.time
represents time. Commonly used attributes include: hour, minute, second, microsecond
datetime.datetime
Represents date and time
datetime.timedelta
Represents the difference between two date, time, datetime instances Time interval, resolution (minimum unit) can reach microseconds
datetime.tzinfo
Abstract base class of time zone related information objects. They are used by the datetime and time classes to provide custom time adjustments.
datetime.timezone
New functionality in Python 3.2, a class that implements the tzinfo abstract base class, representing a fixed offset from UTC
It should be noted that the objects of these classes are immutable.
Relationship between classes:
object
date
datetime
time
timedelta
tzinfo
timezone
Copy after login
2. Constants defined in the datetime module
##Constant name
Description
datetime.MINYEARThe minimum allowed year for datetime.date or datetime.datetime objects, the value is 1
datetime.MAXYEAR
The maximum value of the year allowed by datetime.date or datetime.datetime object is only 9999
3. datetime.date class
Definition of datetime.date class
class datetime.date(year, month, day)
Copy after login
year, month and day are all required parameters, and the value range of each parameter is:
Parameter name
Value range
year[MINYEAR, MAXYEAR]
month
[1, 12]
day
[1, the number of days in the month of the specified year]
Class methods and properties
Class method/property name
Description
date.maxThe maximum date that the date object can represent: 9999-12-31
date.min
The minimum log that the date object can represent: 00001- 01-01
date.resoluation
The minimum unit of date represented by date object: day
##date.today( )
Returns a date object representing the current local date
date.fromtimestamp(timestamp)
Returns a date based on the specified timestamp Object
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn