English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Preface
In the development work, we often need to use the date and time, such as:
Python provides multiple built-in modules for date and time operations: the time module, the datetime module, and the calendar module. The time module is implemented by calling the C library, so some methods may not be available on some platforms, but most of its interfaces are consistent with the C standard library time.h. Compared with the time module, the datetime module provides more intuitive, easy-to-use interfaces, and has more powerful functions.
Chapter I: Explanation of Related Terms
Chapter II: Time Representation
Common time representation is:
There are other time representation forms in Python:
The 'datetime' class of the 'datetime' module will be explained in detail below, here we briefly introduce 'time.struct_time'.
The 'time.struct_time' contains the following attributes:
Subscript/Index | Attribute name | Description |
---|---|---|
0 | tm_year | The year, such as 2017 |
1 | tm_mon | The month, the range of values is [1, 12] |
2 | tm_mday | The day of the month, the range of values is [1-31] |
3 | tm_hour | Hours, the range of values is [0-23] |
4 | tm_min | Minutes, the range of values is [0, 59] |
5 | tm_sec | Seconds, the range of values is [0, 61] |
6 | tm_wday | The day of the week, the range of values is [0-6], 0 represents Monday |
7 | tm_yday | The day of the year, the range of values is [1, 366] |
8 | tm_isdst | Whether it is daylight saving time, which can be: 0 , 1 Or -1 |
There are two ways to obtain attribute values:
It should be noted that all attributes of the 'struct_time' instance are read-only and cannot be modified.
Three, 'time' module
The 'time' module is mainly used for time access and conversion, and this module provides various functions related to time.
1. Function list
Method/Attribute | Description |
---|---|
time.altzone | Returns the time difference with UTC time in seconds (the value is positive in the western region, and negative in the eastern region). It represents the offset of the local DST time zone, and it is only used when 'daylight' is not 0. |
time.clock() | Returns the processor running time consumed by the current process in seconds (excluding sleep time), with a decimal value; this method in Python3.3It has been changed to 'time.process_time()' |
time.asctime([t]) | Converts a tuple or struct_time format of time (which can be obtained through the 'gmtime()' and 'localtime()' methods) into a24A time string with a length of characters, formatted as: "Fri Aug" 19 11:14:16 2016If the parameter 't' is not provided, the return value of 'localtime()' is used as the parameter. |
time.ctime([secs]) | The function is the same as above, which converts a timestamp representing seconds into a string representing the current local time. If the parameter 'secs' is not provided or its 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()} | Return timestamp (since1970-1-1 Seconds elapsed since 0:00:00 to now) |
time.localtime([secs]) | Return struct_time object corresponding to specified timestamp in local time (can be accessed via index or .attribute_name to refer to internal attributes) |
time.localtime(time.time()) + n*3600) | Return struct_time object format (n hours later) in local time (can be used to implement similar crontab functionality) |
time.gmtime([secs]) | Return struct_time object format corresponding to specified timestamp in UTC time (difference from current local time)8hours) |
time.gmtime(time.time()) + n*3600) | Return struct_time object (n hours later) in UTC time format (can be accessed via .attribute_name to refer to internal attributes) |
time.strptime(time_str, time_format_str) | Convert time string to struct_time time object, e.g., time.strptime('2017-01-13 17:07', '%Y-%m-%d %H:%M' |
time.mktime(struct_time_instance) | Convert struct_time object instance to timestamp |
time.strftime(time_format_str, struct_time_instance) | Convert struct_time object instance to string |
2. Practice
Get timestamp format time
>>> time.time() 1486188022.862
Get struct_time format time
>>> time.localtime() time.struct_time(tm_year=2017, tm_mon=2, tm_mday=4, tm_hour=14, tm_min=2, tm_sec=34, tm_wday=5, tm_yday=35, tm_isdst=0) >>> time.gmtime() time.struct_time(tm_year=2017, tm_mon=2, tm_mday=4, tm_hour=6, tm_min=2, tm_sec=56, tm_wday=5, tm_yday=35, tm_isdst=0)
Get string format time
>>> time.ctime() 'Sat Feb 04 14:06:42 2017' >>> time.asctime() 'Sat Feb 04 14:06:47 2017'
Timestamp format to struct_time format time
>>> t1 = time.time() >>> print(t1 1486188476.9 >>> t2 = time.localtime(t1 >>> print(t2 time.struct_time(tm_year=2017, tm_mon=2, tm_mday=4, tm_hour=14, tm_min=7, tm_sec=56, tm_wday=5, tm_yday=35, tm_isdst=0) >>> t3 = time.gmtime(t1 >>> print(t3 time.struct_time(tm_year=2017, tm_mon=2, tm_mday=4, tm_hour=6, tm_min=7, tm_sec=56, tm_wday=5, tm_yday=35, tm_isdst=0) >>>
String format to struct_time format time
>>> time.strptime('Sat Feb 04 14:06:42 2017) time.struct_time(tm_year=2017, tm_mon=2, tm_mday=4, tm_hour=14, tm_min=6, tm_sec=42, tm_wday=5, tm_yday=35, tm_isdst=-1 >>> time.strptime('Sat Feb 04 14:06:42 2017', '%a %b %d %H:%M:%S %Y') time.struct_time(tm_year=2017, tm_mon=2, tm_mday=4, tm_hour=14, tm_min=6, tm_sec=42, tm_wday=5, tm_yday=35, tm_isdst=-1 >>> time.strptime('2017-02-04 14:12', '%Y-%m-%d %H:%M' time.struct_time(tm_year=2017, tm_mon=2, tm_mday=4, tm_hour=14, tm_min=12, tm_sec=0, tm_wday=5, tm_yday=35, tm_isdst=-1 >>> time.strptime('2017/02/04 14:12', '%Y/%m/%d %H:%M' time.struct_time(tm_year=2017, tm_mon=2, tm_mday=4, tm_hour=14, tm_min=12, tm_sec=0, tm_wday=5, tm_yday=35, tm_isdst=-1 >>> time.strptime('201702041412', '%Y%m%d%H%M') time.struct_time(tm_year=2017, tm_mon=2, tm_mday=4, tm_hour=14, tm_min=12, tm_sec=0, tm_wday=5, tm_yday=35, tm_isdst=-1
struct_time format to string format time
>>> time.strftime('%Y-%m->>> time.strftime('%d %H:%M', time.localtime()) '2017-02-04 14:19' struct_time format to timestamp format time >>> time.mktime(time.localtime()) 1486189282.0
3. Time format conversion
Although the timestamp format of time and the string format of time can be converted through the ctime([secs]) method, the string format is not very suitable for the national conditions of China. Therefore, in general, they cannot be converted directly and need to be converted through struct_time as an intermediary, the conversion relationship is as follows:
Note: '%H:%M:%S' above can be replaced directly with '%X'.
Chapter IV: datetime module
The datetime module provides classes for handling dates and times, with both simple and complex methods. Although it supports date and time algorithms, its focus is on providing efficient attribute extraction features 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 a date, common properties include: year, month, and day |
datetime.time | Represents time, common properties include: hour, minute, second, microsecond |
datetime.datetime | Represents date and time |
datetime.timedelta | Represents the time interval between two date, time, and datetime instances, with a resolution (minimum unit) as fine as microseconds |
datetime.tzinfo | The abstract base class for objects related to time zones. They are used by the datetime and time classes to provide adjustments for custom time. |
datetime.timezone | Python 3.2A class that implements the tzinfo abstract base class added in, 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
2Constants defined in the datetime module
constant name | Description |
---|---|
datetime.MINYEAR | The minimum value of the year allowed for datetime.date or datetime.datetime objects is1 |
datetime.MAXYEAR | The maximum year allowed for datetime.date or datetime.datetime objects, which is only9999 |
3. datetime.date class
Definition of datetime.date class
class datetime.date(year, month, day)
year, month, and day are all required parameters, and the range of values for each parameter is:
Parameter name | Value range |
---|---|
year | [MINYEAR, MAXYEAR] |
month | [1, 12] |
day | [1, the day of the month of the specified year] |
class methods and properties
class method/Attribute name | Description |
---|---|
date.max | The largest date that the date object can represent:9999-12-31 |
date.min | The smallest unit of time that the date object can represent: 00001-01-01 |
date.resolution | The smallest unit of the date represented by the date object: day |
date.today() | Returns a date object representing the current local date |
date.fromtimestamp(timestamp) | Returns a date object based on a specified timestamp |
object methods and properties
object method/Attribute name | Description |
---|---|
d.year | Year |
d.month | Month |
d.day | Day |
d.replace(year[, month[, day]]) | Generates and returns a new date object without changing the original date object |
d.timetuple() | Returns the time.struct_time object corresponding to the date |
d.toordinal() | Returns the date since 0001-01-01 The day of the year |
d.weekday() | Returns the day of the week, [0, 6], 0 represents Monday |
d.isoweekday() | Returns the day of the week, [1, 7], 1Represents Monday |
d.isocalendar() | Returns a tuple, formatted as: (year, weekday, isoweekday) |
d.isoformat() | Returns 'YYYY'-MM-Date string in 'DD' format |
d.strftime(format) | Returns a date string in a specified format, similar to the strftime(format, struct_time) function of the time module |
Example
>>> import time >>> from datetime import date >>> >>> date.max datetime.date(9999, 12, 31 >>> date.min datetime.date(1, 1, 1 >>> date.resolution datetime.timedelta(1 >>> date.today() datetime.date(2017, 2, 4 >>> date.fromtimestamp(time.time()) datetime.date(2017, 2, 4 >>> >>> d = date.today() >>> d.year 2017 >>> d.month 2 >>> d.day 4 >>> d.day2016 datetime.date(2016, 2, 4 >>> d.day2016, 3 >>> d.day2016, 3, 2 datetime.date(2016, 3, 2 >>> d.replace( time.struct_time(tm_year=2017, tm_mon=2, tm_mday=4>>> d.timetuple()5, tm_yday=35, tm_isdst=-1 , tm_hour=0, tm_min=0, tm_sec=0, tm_wday= 736364 >>> d.toordinal() 5 >>> d.weekday() 6 >>> d.isoweekday() (2017, 5, 6 >>> d.isocalendar() '2017-02-04' >>> d.isoformat() 'Sat Feb 4 >>> d.ctime() 2017' 00:00:00/%m/>>> d.strftime('%Y '2017/02/04'
4. datetime.time class
Definition of time class
class datetime.time(hour, [minute[, second, [microsecond[, tzinfo]]]])
hour is a required parameter, and the others are optional. The range of values for each parameter is:
Parameter name | Value range |
---|---|
hour | [0, 23] |
minute | [0, 59] |
second | [0, 59] |
microsecond | [0, 1000000] |
tzinfo | Subclass objects of tzinfo, such as instances of the timezone class |
class methods and properties
class method/Attribute name | Description |
---|---|
time.max | The largest time that the time class can represent: time(23, 59, 59, 999999 |
time.min | The smallest time that the time class can represent: time(0, 0, 0, 0) |
time.resolution | The smallest unit of time, which is the minimum difference between two different times:1Microsecond |
object methods and properties
object method/Attribute name | Description |
---|---|
t.hour | Hour |
t.minute | Minute |
t.second | Second |
t.microsecond | Microsecond |
t.tzinfo | Returns the tzinfo object passed to the time constructor method, or None if the parameter is not provided |
t.replace(hour[, minute[, second[, microsecond[, tzinfo]]]]) | Generates and returns a new time object without changing the original time object |
t.isoformat() | Returns a time string in the 'HH:MM:SS.%f' format |
t.strftime() | Returns a time string in the specified format, similar to the strftime(format, struct_time) function of the time module |
Example
>>> from datetime import time >>> >>> time.max datetime.time(23, 59, 59, 999999 >>> time.min datetime.time(0, 0) >>> time.resolution datetime.timedelta(0, 0, 1 >>> >>> t = time(20, 5, 40, 8888 >>> t.hour 20 >>> t.minute 5 >>> t.second 40 >>> t.microsecond 8888 >>> t.tzinfo >>> >>> t.replace21 datetime.time(21, 5, 40, 8888 >>> t.isoformat() '20:05:40.008888' >>> t.strftime('%H%M%S') '200540' >>> t.strftime('%H%M%S.%f') '200540.008888'
5. datetime.datetime class
Definition of datetime class
class datetime.datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None)
year, month, and day are required parameters, tzinfo can be None or an instance of a tzinfo subclass.
The value range of each parameter is as follows:
Parameter name | Value range |
---|---|
year | [MINYEAR, MAXYEAR] |
month | [1, 12] |
day | [1, the day of the month of the specified year] |
hour | [0, 23] |
minute | [0, 59] |
second | [0, 59] |
microsecond | [0, 1000000] |
tzinfo | Subclass objects of tzinfo, such as instances of the timezone class |
If a parameter exceeds these ranges, it will raise a ValueError exception.
class methods and properties
class method/Attribute name | Description |
---|---|
datetime.today() | Return a datetime object representing the current period date and time |
datetime.now([tz]) | Return a datetime object representing the specified timezone date and time, if the tz parameter is not specified, the result is the same as above |
datetime.utcnow() | Return a datetime object representing the current UTC date and time |
datetime.fromtimestamp(timestamp[, tz]) | Create a datetime object based on a specified timestamp |
datetime.utcfromtimestamp(timestamp) | Create a datetime object based on a specified timestamp |
datetime.combine(date, time) | Combine a specified date and time object into a datetime object |
datetime.strptime(date_str, format) | Convert a time string to a datetime object |
object methods and properties
object method/Attribute name | Description |
---|---|
dt.year, dt.month, dt.day | year, month, day |
dt.hour, dt.minute, dt.second | hour, minute, second |
dt.microsecond, dt.tzinfo | Microseconds, timezone information |
dt.date() | Gets the date object corresponding to the datetime object |
dt.time() | Gets the time object corresponding to the datetime object, tzinfo is None |
dt.timetz() | Gets the time object corresponding to the datetime object, tzinfo is the same as the datetime object's tzinfo |
dt.replace([year[, month[, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]]]]]) | Generates and returns a new datetime object, if all parameters are not specified, it returns an object identical to the original datetime object |
dt.timetuple() | Returns a tuple corresponding to the datetime object (excluding tzinfo) |
dt.utctimetuple() | Returns a tuple of UTC time corresponding to the datetime object (excluding tzinfo) |
dt.toordinal() | Same as date object |
dt.weekday() | Same as date object |
dt.isocalendar() | Shared exclusively with date |
dt.isoformat([sep]) | Returns a '%Y-%m-%d |
dt.ctime() | Equivalent to time module's time.ctime(time.mktime(d.timetuple())) |
dt.strftime(format) | Return a time string in specified format |
Example
>>> from datetime import datetime, timezone >>> >>> datetime.today() datetime.datetime(2017, 2, 4, 20, 44, 40, 556318 >>> datetime.now() datetime.datetime(2017, 2, 4, 20, 44, 56, 572615 >>> datetime.now(timezone.utc) datetime.datetime(2017, 2, 4, 12, 45, 22, 881694, tzinfo=datetime.timezone.utc) >>> datetime.utcnow() datetime.datetime(2017, 2, 4, 12, 45, 52, 812508 >>> import time >>> datetime.fromtimestamp(time.time()) datetime.datetime(2017, 2, 4, 20, 46, 41, 97578 >>> datetime.utcfromtimestamp(time.time()) datetime.datetime(2017, 2, 4, 12, 46, 56, 989413 >>> datetime.combine(date(2017, 2, 4), t) datetime.datetime(2017, 2, 4, 20, 5, 40, 8888 >>> datetime.strptime('2017/02/04 20:49', '%Y/%m/%d %H:%M' datetime.datetime(2017, 2, 4, 20, 49 >>> dt = datetime.now() >>> dt datetime.datetime(2017, 2, 4, 20, 57, 0, 621378 >>> dt.year 2017 >>> dt.month 2 >>> dt.day 4 >>> dt.hour 20 >>> dt.minute 57 >>> dt.second 0 >>> dt.microsecond 621378 >>> dt.tzinfo >>> dt.timestamp() 1486213020.621378 >>> dt.date() datetime.date(2017, 2, 4 >>> dt.time() datetime.time(20, 57, 0, 621378 >>> dt.timetz() datetime.time(20, 57, 0, 621378 >>> dt.replace() datetime.datetime(2017, 2, 4, 20, 57, 0, 621378 >>> dt.replace(2016 datetime.datetime(2016, 2, 4, 20, 57, 0, 621378 >>> dt.timetuple() time.struct_time(tm_year=2017, tm_mon=2, tm_mday=4, tm_hour=20, tm_min=57, tm_sec=0, tm_wday=5, tm_yday=35, tm_isdst=-1 >>> dt.utctimetuple() time.struct_time(tm_year=2017, tm_mon=2, tm_mday=4, tm_hour=20, tm_min=57, tm_sec=0, tm_wday=5, tm_yday=35, tm_isdst=0) >>> dt.toordinal() 736364 >>> dt.weekday() 5 >>> dt.isocalendar() (2017, 5, 6 >>> dt.isoformat() '2017-02-04T20:57:00.621378' >>> dt.isoformat(sep='/) '2017-02-04/20:57:00.621378' >>> dt.isoformat(sep=' ') '2017-02-04 20:57:00.621378' >>> dt.ctime() 'Sat Feb 4 20:57:00 2017' >>> dt.strftime('%Y%m%d %H:%M:%S.%f') '20170204 20:57:00.621378'
6. Use datetime.datetime class to convert timestamp and time string
7. datetime.timedelta class
The timedelta object represents the difference between two different times. If time arithmetic operations are performed using the time module, only string format time and struct_time format time objects need to be converted to timestamp format first, then n seconds are added or subtracted from the timestamp, and finally converted back to struct_time format or string format. This is obviously very inconvenient. However, the timedelta class provided by the datetime module allows us to easily perform arithmetic operations on datetime.date, datetime.time, and datetime.datetime objects, and the unit of the difference between two times is also easier to control.
The unit of this difference can be: day, second, microsecond, millisecond, minute, hour, week.
Definition of datetime.timedelta class
class datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, hours=0, weeks=0)
All parameters are default parameters, therefore they are optional. The value of the parameter can be an integer or a floating-point number, it can also be positive or negative. The internal value stores days, seconds and microseconds, and all other parameters will be converted to this3units:
Then convert these3Normalize the values of these
Class attribute
Class attribute name | Description |
---|---|
timedelta.min | timedelta(-999999999 |
timedelta.max | timedelta(days=999999999, hours=23, minutes=59, seconds=59, microseconds=999999 |
timedelta.resolution | timedelta(microseconds=1 |
Instance methods and attributes
Instance method/Attribute name | Description |
---|---|
td.days | Days [-999999999, 999999999] |
td.seconds | Seconds [0, 86399] |
td.microseconds | Microseconds [0, 999999] |
td.total_seconds() | Total seconds contained in the time difference, equivalent to: td / timedelta(seconds=1 |
Method/Attribute | Description |
---|---|
datetime.datetime.now() | Returns the current local time (an instance of datetime.datetime object) |
datetime.datetime.fromtimestamp(timestamp) | Returns the time corresponding to a specified timestamp (an instance of datetime.datetime object) |
datetime.timedelta() | Returns a timedelta object that can be directly added or subtracted with datetime.datetime objects |
Example
>>> import datetime >>> >>> datetime.timedelta(365).total_seconds() # Total seconds in a year 31536000.0 >>> dt = datetime.datetime.now() >>> dt + datetime.timedelta(3) # 3after datetime.datetime(2017, 2, 8, 9, 39, 40, 102821 >>> dt + datetime.timedelta(-3) # 3days ago datetime.datetime(2017, 2, 2, 9, 39, 40, 102821 >>> dt + datetime.timedelta(hours=3) # 3hours later datetime.datetime(2017, 2, 5, 12, 39, 40, 102821 >>> dt + datetime.timedelta(hours=-3) # 3hours ago datetime.datetime(2017, 2, 5, 6, 39, 40, 102821 >>> dt + datetime.timedelta(hours=3, seconds=30) # 3hours30 seconds later datetime.datetime(2017, 2, 5, 12, 40, 10, 102821
5. Time Format Codes
The struct_time of the time module and the datetime, date, and time classes of the datetime module both provide the strftime() method, which can output a time string in a specified format. The specific format is composed of a series of format codes (format characters), and Python ultimately calls the strftme() function of the C library of each platform, so there will be differences in the support of the full set of format codes on each platform. The specific situation needs to be referred to in the strftime() of the platform.3Document. The following lists the C standard (1989Format codes required by the standard C implementation platform:
6. Summary
When dealing with time in Python, is it better to use the time module or the datetime module? As for me, the datetime module can basically meet the needs and is indeed more convenient to use. For the time module, I only use the time.time() method when I need to get the timestamp of the current time, of course, I can also get it through datetime.datetime.now().timestamp(), but it seems a bit more complicated. I think it still depends on personal habits, and there is no absolute good or bad.
That's all for this article. I hope it will be helpful to everyone's learning, and I also hope everyone will support the Yelling Tutorial more.
Statement: The content of this article is from the Internet, and the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, does not undergo manual editing, and does not assume relevant legal liability. If you find any content suspected of copyright infringement, please send an email to: notice#oldtoolbag.com (When reporting, please replace # with @) for reporting, and provide relevant evidence. Once verified, this site will immediately delete the infringing content.