Home  >  Article  >  Backend Development  >  Python date and time processing module (date and datetime)

Python date and time processing module (date and datetime)

高洛峰
高洛峰Original
2017-02-20 10:10:581170browse

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 nameDescription##012##3tm_hourhours, the value range is [0-23]4tm_minminutes, the value range is [0, 59]5tm_sec seconds, the value range is [0, 61]6tm_wdayThe day of the week, the value range is [0-6], 0 means Monday7tm_ydayThe day of the year, the value range is [1, 366]tm_isdst
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]
##8
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/PropertyDescriptiontime.altzoneReturns 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) formattime.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) formattime.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.strftime(time_format_str, struct_time_instance)

2. Exercise

Get the time in timestamp format

>>> time.time()
1486188022.862

Get the time in struct_time format

>>> 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 the time in string format

>>> time.ctime()
'Sat Feb 04 14:06:42 2017'
>>> time.asctime()
'Sat Feb 04 14:06:47 2017'

Time stamp 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)
>>>

Convert 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)

Convert struct_time format to string format time

>>> time.strftime('%Y-%m-%d %H:%M', time.localtime())
'2017-02-04 14:19'

struct_time格式转时间戳格式时间
>>> time.mktime(time.localtime())
1486189282.0

3. Time format conversion

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:

Python date and time processing module (date and datetime)

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:


Convert struct_time object instance to string
Class nameDescription##datetime.date##datetime.time represents time. Commonly used attributes include: hour, minute, second, microseconddatetime.datetimeRepresents date and timedatetime.timedeltaRepresents the difference between two date, time, datetime instances Time interval, resolution (minimum unit) can reach microsecondsdatetime.tzinfoAbstract base class of time zone related information objects. They are used by the datetime and time classes to provide custom time adjustments. datetime.timezoneNew functionality in Python 3.2, a class that implements the tzinfo abstract base class, representing a fixed offset from UTCIt should be noted that the objects of these classes are immutable.
represents date, commonly used Attributes include: year, month and day
Relationship between classes:


object
 date
 datetime
 time
 timedelta
 tzinfo
 timezone

2. Constants defined in the datetime module



##Constant nameDescriptiondatetime.MINYEARThe minimum allowed year for datetime.date or datetime.datetime objects, the value is 1The maximum value of the year allowed by datetime.date or datetime.datetime object is only 99993. datetime.date class
datetime.MAXYEAR

Definition of datetime.date class

class datetime.date(year, month, day)

year, month and day are all required parameters, and the value range of each parameter is:


Parameter nameValue rangeyear[MINYEAR, MAXYEAR][1, 12][1, the number of days in the month of the specified year]Class methods and properties
month
day



Class method/property nameDescriptiondate.maxThe maximum date that the date object can represent: 9999-12-31The minimum log that the date object can represent: 00001- 01-01The minimum unit of date represented by date object: day##date.today( )Returns a date object representing the current local datedate.fromtimestamp(timestamp)Returns a date based on the specified timestamp Object

对象方法和属性


date.min
date.resoluation
对象方法/属性名称 描述
d.year
d.month
d.day
d.replace(year[, month[, day]]) 生成并返回一个新的日期对象,原日期对象不变
d.timetuple() 返回日期对应的time.struct_time对象
d.toordinal() 返回日期是是自 0001-01-01 开始的第多少天
d.weekday() 返回日期是星期几,[0, 6],0表示星期一
d.isoweekday() 返回日期是星期几,[1, 7], 1表示星期一
d.isocalendar() 返回一个元组,格式为:(year, weekday, isoweekday)
d.isoformat() 返回‘YYYY-MM-DD'格式的日期字符串
d.strftime(format) 返回指定格式的日期字符串,与time模块的strftime(format, struct_time)功能相同

实例

>>> 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为必须参数,其他为可选参数。各参数的取值范围为:


参数名称 取值范围
hour [0, 23]
minute [0, 59]
second [0, 59]
microsecond [0, 1000000]
tzinfo tzinfo的子类对象,如timezone类的实例

类方法和属性


类方法/属性名称 描述
time.max time类所能表示的最大时间:time(23, 59, 59, 999999)
time.min time类所能表示的最小时间:time(0, 0, 0, 0)
time.resolution 时间的最小单位,即两个不同时间的最小差值:1微秒

对象方法和属性


对象方法/属性名称 描述
t.hour
t.minute
t.second
t.microsecond 微秒
t.tzinfo 返回传递给time构造方法的tzinfo对象,如果该参数未给出,则返回None
t.replace(hour[, minute[, second[, microsecond[, tzinfo]]]]) 生成并返回一个新的时间对象,原时间对象不变
t.isoformat() 返回一个‘HH:MM:SS.%f'格式的时间字符串
t.strftime() 返回指定格式的时间字符串,与time模块的strftime(format, struct_time)功能相同

实例

>>> 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子类的实例。

各参数的取值范围为:


参数名称 取值范围
year [MINYEAR, MAXYEAR]
month [1, 12]
day [1, 指定年份的月份中的天数]
hour [0, 23]
minute [0, 59]
second [0, 59]
microsecond [0, 1000000]
tzinfo tzinfo的子类对象,如timezone类的实例

If a parameter exceeds these ranges, a ValueError exception will be caused.

Class methods and properties


#Class method/property nameDescriptiondatetime.today()Returns a datetime object representing the current date and timedatetime.now([tz])Returns the datetime object of the specified time zone date and time. If the tz parameter is not specified, the result is the same as abovedatetime.utcnow() Return the datetime object of the current UTC date and time datetime.fromtimestamp(timestamp[, tz])Create a datetime object based on the specified timestamp datetime.utcfromtimestamp(timestamp)Create a datetime object based on the specified timestampdatetime.combine(date , time)Integrate the specified date and time objects into a datetime objectdatetime.strptime(date_str, format)Convert the time characters Convert string to datetime object
Object methods and properties



Object method/property nameDescriptiondt.year, dt.month, dt.dayyear, Month, daydt.hour, dt.minute, dt.secondHour, minute, seconddt .microsecond, dt.tzinfoMicrosecond, time zone informationdt.date()Get the date object corresponding to the datetime objectdt.time()Get the time object corresponding to the datetime object, tzinfo is Nonedt.timetz()Get the time object corresponding to the datetime object, tzinfo is the same as the tzinfo of the datetime object##dt.replace([year[, month[, day[, hour[, minute[ , second[, microsecond[, tzinfo]]]]]]])dt.timetuple()dt.utctimetuple() dt.toordinal()dt.weekday()dt.isocalendar()dt.isoformat([sep])dt.ctime ()##dt.strftime(format) of the time module Return the time string in the specified format

实例

>>> 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类对时间戳与时间字符串进行转换

Python date and time processing module (date and 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个单位:

  • 1毫秒转换为1000微秒

  • 1分钟转换为60秒

  • 1小时转换为3600秒

  • 1周转换为7天

然后对这3个值进行标准化,使得它们的表示是唯一的:

  • microseconds : [0, 999999]

  • seconds : [0, 86399]

  • days : [-999999999, 999999999]

类属性


Generate and return a new datetime object. If all parameters are not specified, return an object that is the same as the original datetime object
Returns the tuple corresponding to the datetime object (excluding tzinfo)
Returns the tuple of UTC time corresponding to the datetime object (excluding tzinfo)
Same as the date object
Same date object
Same date exclusive
Returns a '%Y-%m-%d
Equivalent to time.ctime(time.mktime(d.timetuple()))
类属性名称 描述
timedelta.min timedelta(-999999999)
timedelta.max timedelta(days=999999999, hours=23, minutes=59, seconds=59, microseconds=999999)
timedelta.resolution timedelta(microseconds=1)

实例方法和属性


实例方法/属性名称 描述
td.days 天 [-999999999, 999999999]
td.seconds 秒 [0, 86399]
td.microseconds 微秒 [0, 999999]
td.total_seconds() 时间差中包含的总秒数,等价于: td / timedelta(seconds=1)


方法/属性 描述
datetime.datetime.now() 返回当前本地时间(datetime.datetime对象实例)
datetime.datetime.fromtimestamp(timestamp) 返回指定时间戳对应的时间(datetime.datetime对象实例)
datetime.timedelta() 返回一个时间间隔对象,可以直接与datetime.datetime对象做加减操作

实例

>>> 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 date and time processing module (date and datetime)

六、总结

那么Python中处理时间时,使用time模块好,还是用datetime模块好呢?就我个人而言,datetime模块基本上可以满足需要,且用起来确实比较方便。对于time模块,我只是在取当前时间的时间戳时会用到time.time()方法,当然也可以通过datetime.datetime.now().timestamp()来获取,只是显得复杂一点。我觉得还是看个人习惯吧,没有什么绝对的好坏之分。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持PHP中文网。

更多Python date and time processing module (date and datetime)相关文章请关注PHP中文网!

Statement:
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