Home > Article > Backend Development > Python datetime and date modules
This article mainly introduces the date and time processing module (date and datetime) of Python. The editor thinks it is quite good. Now I will share it with you and give it as a reference. Let’s follow the editor and take a look.
Preface
In development work, we often need to use date and time, such as:
Output as the content of log information
Calculate the execution time of a certain function
Use date Name a log file
Record or display the publication or modification time of an article
Others
Python provides multiple built-in modules for operating on dates and times: 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 the time since January 1, 1970 GMT The number of milliseconds that have elapsed since 0:00:00, and its value is of type float. However, some programming languages related methods return the number of seconds (this is the case with Python). You need to see 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:
Timestamp
Formatted timeString
There are also in Python Other time representations:
time.struct_time of the time module
datetime class of the datetime module
The datetime class of the datetime module will be explained in detail below. Here is a brief introduction to time.struct_time.
time.struct_time contains the following attributes:
Index | Attribute nameDescription | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
tm_year | Year, such as 2017 | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
tm_mon | Month, the value range is [1, 12] | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
tm_mday | The day of the month, the value range is [1-31] | ##3 | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
hours, the value range is [0-23] | 4 | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
minutes, the value range is [0, 59] | 5 | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
seconds, the value range is [0, 61] | 6 | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
The day of the week, the value range is [0-6], 0 means Monday | 7 | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
The day of the year, the value range is [1, 366] | ##8 | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Whether it is daylight saving time, the possible values are: 0, 1 or -1 |
There are two ways to obtain attribute values:
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 function. 1. Function list
object date datetime time timedelta tzinfo timezone 2. Constant defined in datetime module
3. datetime.date class Definition of datetime.date classclass datetime.date(year, month, day)year, month and day All are required parameters. The value range of each parameter is:
实例 >>> 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.replace(2016) datetime.date(2016, 2, 4) >>> d.replace(2016, 3) >>> d.replace(2016, 3, 2) datetime.date(2016, 3, 2) >>> d.timetuple() time.struct_time(tm_year=2017, tm_mon=2, tm_mday=4, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=5, tm_yday=35, tm_isdst=-1) >>> d.toordinal() 736364 >>> d.weekday() 5 >>> d.isoweekday() 6 >>> d.isocalendar() (2017, 5, 6) >>> d.isoformat() '2017-02-04' >>> d.ctime() 'Sat Feb 4 00:00:00 2017' >>> d.strftime('%Y/%m/%d') '2017/02/04' 4. datetime.time类 time类的定义 class datetime.time(hour, [minute[, second, [microsecond[, tzinfo]]]]) hour为必须参数,其他为可选参数。各参数的取值范围为:
类方法和属性
对象方法和属性
实例 >>> 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.replace(21) 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类 datetime类的定义 代码如下: class datetime.datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None) year, month 和 day是必须要传递的参数, tzinfo可以是None或tzinfo子类的实例。 各参数的取值范围为:
如果一个参数超出了这些范围,会引起ValueError异常。 类方法和属性
对象方法和属性
实例 >>> 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. 使用datetime.datetime类对时间戳与时间字符串进行转换 7. datetime.timedelta类 timedelta对象表示连个不同时间之间的差值。如果使用time模块对时间进行算术运行,只能将字符串格式的时间 和 struct_time格式的时间对象 先转换为时间戳格式,然后对该时间戳加上或减去n秒,最后再转换回struct_time格式或字符串格式,这显然很不方便。而datetime模块提供的timedelta类可以让我们很方面的对datetime.date, datetime.time和datetime.datetime对象做算术运算,且两个时间之间的差值单位也更加容易控制。 datetime.timedelta类的定义 代码如下: class datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, hours=0, weeks=0) 所有参数都是默认参数,因此都是可选参数。参数的值可以是整数或浮点数,也可以是正数或负数。内部值存储days、seconds 和 microseconds,其他所有参数都将被转换成这3个单位:
然后对这3个值进行标准化,使得它们的表示是唯一的:
类属性
实例方法和属性
实例 >>> import datetime >>> >>> datetime.timedelta(365).total_seconds() # 一年包含的总秒数 31536000.0 >>> dt = datetime.datetime.now() >>> dt + datetime.timedelta(3) # 3天后 datetime.datetime(2017, 2, 8, 9, 39, 40, 102821) >>> dt + datetime.timedelta(-3) # 3天前 datetime.datetime(2017, 2, 2, 9, 39, 40, 102821) >>> dt + datetime.timedelta(hours=3) # 3小时后 datetime.datetime(2017, 2, 5, 12, 39, 40, 102821) >>> dt + datetime.timedelta(hours=-3) # 3小时前 datetime.datetime(2017, 2, 5, 6, 39, 40, 102821) >>> dt + datetime.timedelta(hours=3, seconds=30) # 3小时30秒后 datetime.datetime(2017, 2, 5, 12, 40, 10, 102821) 五、时间格式码 time模块的struct_time以及datetime模块的datetime、date、time类都提供了strftime()方法,该方法可 以输出一个指定格式的时间字符串。具体格式由一系列的格式码(格式字符)组成,Python最终调用的是各个平台C库的strftme()函数,因此各平台对全套格式码的支持会有所不同,具体情况需要参考该平台上的strftime(3)文档。下面列出了C标准(1989版)要求的所有格式码,它们在所有标准C实现的平台上都可以工作: 六、总结 那么Python中处理时间时,使用time模块好,还是用datetime模块好呢?就我个人而言,datetime模块基本上可以满足需要,且用起来确实比较方便。对于time模块,我只是在取当前时间的时间戳时会用到time.time()方法,当然也可以通过datetime.datetime.now().timestamp()来获取,只是显得复杂一点。我觉得还是看个人习惯吧,没有什么绝对的好坏之分。 【相关推荐】 1. Python免费视频教程 2. Python学习手册 |
The above is the detailed content of Python datetime and date modules. For more information, please follow other related articles on the PHP Chinese website!