Compared with the time module, the interface of the datetime module is more intuitive and easier to call. Today let’s talk about the datetime module.
The datetime module defines two constants: datetime.MINYEAR and datetime.MAXYEAR, which respectively represent the minimum and maximum year that datetime can represent. Among them, MINYEAR = 1, MAXYEAR = 9999. (For casual players, this range is enough~~)
The datetime module defines the following classes:
•datetime.date: a class representing dates. Commonly used attributes include year, month, day;
•datetime.time: a class representing time. Commonly used attributes include hour, minute, second, microsecond;
•datetime.datetime: represents date and time.
•datetime.timedelta: represents the time interval, that is, the length between two time points.
•datetime.tzinfo: Related information related to time zone. (This class will not be fully discussed in detail here. Interested children can refer to the python manual)
Note: The above types of objects are all immutable.
The following describes how to use these classes in detail.
date class
The date class represents a date. The date consists of year, month and day (everyone on earth knows~~). The constructor of the date class is as follows:
class datetime.date(year, month, day): The meaning of the parameters will not be explained much, but there are a few points to pay attention to:
• The range of year is [MINYEAR, MAXYEAR], that is, [1, 9999];
•The range of month is [1, 12]. (The month starts from 1, not from 0~_~);
•The maximum value of day is determined according to the given year and month parameters. For example, February in a leap year has 29 days;
The date class defines some commonly used class methods and class attributes to facilitate our operations:
•date.max, date.min: the maximum value that the date object can represent , Minimum date;
•date.resolution: The date object represents the minimum unit of date. Here is the sky.
•date.today(): Returns a date object representing the current local date;
•date.fromtimestamp(timestamp): Returns a date object based on the given time stamp;
•datetime.fromordinal (ordinal): Convert Gregorian calendar time into a date object; (Gregorian Calendar: a calendar representation method, similar to our country’s lunar calendar, which is commonly used in Western countries and will not be discussed in detail here.)
Use Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
Instance methods and attributes provided by date:
•date.year, date.month, date.day: year, month, day;
•date.replace( year, month, day): Generate a new date object, replacing the attributes in the original object with the year, month, and day specified by the parameters. (The original object remains unchanged)
•date.timetuple(): Returns the time.struct_time object corresponding to the date;
•date.toordinal(): Returns the Gregorian Calendar date corresponding to the date;
• date.weekday(): Returns weekday, if it is Monday, returns 0; if it is Tuesday, returns 1, and so on;
•data.isoweekday(): Returns weekday, if it is Monday, returns 1; If it is the 2nd of the week, return 2, and so on;
•date.isocalendar(): Return a tuple in the format such as (year, month, day);
•date.isoformat(): Return the format such as ' YYYY-MM-DD' string;
•date.strftime(fmt): Custom format string. Explain in detail below.
Usage example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
|
date also overloads certain operations, which allows us to perform the following operations on dates:
•date2 = date1 + timedelta # Add an interval to the date and return a new date object (timedelta will be introduced below to represent the time interval)
•date2 = date1 - timedelta # Remove the interval from the date and return a new date object
•timedelta = date1 - date2 # Subtract two dates and return a time interval object
•date1 < date2 # Compare two dates
Note: When operating on dates, be sure to prevent the date from exceeding the range it can represent. .
Usage example:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
Time类
time类表示时间,由时、分、秒以及微秒组成。(我不是从火星来的~~)time类的构造函数如下:
class datetime.time(hour[, minute[, second[, microsecond[, tzinfo]]]]) :各参数的意义不作解释,这里留意一下参数tzinfo,它表示时区信息。注意一下各参数的取值范围:hour的范围为[0, 24),minute的范围为[0, 60),second的范围为[0, 60),microsecond的范围为[0, 1000000)。
time类定义的类属性:
•time.min、time.max:time类所能表示的最小、最大时间。其中,time.min = time(0, 0, 0, 0), time.max = time(23, 59, 59, 999999);
•time.resolution:时间的最小单位,这里是1微秒;
time类提供的实例方法和属性:
•time.hour、time.minute、time.second、time.microsecond:时、分、秒、微秒;
•time.tzinfo:时区信息;
•time.replace([hour[, minute[, second[, microsecond[, tzinfo]]]]]):创建一个新的时间对象,用参数指定的时、分、秒、微秒代替原有对象中的属性(原有对象仍保持不变);
•time.isoformat():返回型如"HH:MM:SS"格式的字符串表示;
•time.strftime(fmt):返回自定义格式化字符串。在下面详细介绍;
使用例子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
|
像date一样,也可以对两个time对象进行比较,或者相减返回一个时间间隔对象。这里就不提供例子了。
datetime类
datetime是date与time的结合体,包括date与time的所有信息。它的构造函数如下:datetime.datetime(year, month, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]]),各参数的含义与date、time的构造函数中的一样,要注意参数值的范围。
datetime类定义的类属性与方法:
•datetime.min、datetime.max:datetime所能表示的最小值与最大值;
•datetime.resolution:datetime最小单位;
•datetime.today():返回一个表示当前本地时间的datetime对象;
•datetime.now([tz]):返回一个表示当前本地时间的datetime对象,如果提供了参数tz,则获取tz参数所指时区的本地时间;
•datetime.utcnow():返回一个当前utc时间的datetime对象;
•datetime.fromtimestamp(timestamp[, tz]):根据时间戮创建一个datetime对象,参数tz指定时区信息;
•datetime.utcfromtimestamp(timestamp):根据时间戮创建一个datetime对象;
•datetime.combine(date, time):根据date和time,创建一个datetime对象;
•datetime.strptime(date_string, format):将格式字符串转换为datetime对象;
使用例子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
|
datetime类提供的实例方法与属性(很多属性或方法在date和time中已经出现过,在此有类似的意义,这里只罗列这些方法名,具体含义不再逐个展开介绍,可以参考上文对date与time类的讲解。):
•datetime.year、month、day、hour、minute、second、microsecond、tzinfo:
•datetime.date():获取date对象;
•datetime.time():获取time对象;
•datetime.replace([year[, month[, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]]]]]):
•datetime.timetuple()
•datetime.utctimetuple()
•datetime.toordinal()
•datetime.weekday()
•datetime.isocalendar()
•datetime.isoformat([sep])
•datetime.ctime():返回一个日期时间的C格式字符串,等效于time.ctime(time.mktime(dt.timetuple()));
•datetime.strftime(format)
像date一样,也可以对两个datetime对象进行比较,或者相减返回一个时间间隔对象,或者日期时间加上一个间隔返回一个新的日期时间对象。这里不提供详细的例子,看客自己动手试一下~~
格式字符串
datetime、date、time都提供了strftime()方法,该方法接收一个格式字符串,输出日期时间的字符串表示。下表是从python手册中拉过来的,我对些进行了简单的翻译(翻译的有点噢口~~)。
格式字符 意义
%a星期的简写。如 星期三为Web
%A星期的全写。如 星期三为Wednesday
%b月份的简写。如4月份为Apr
%B月份的全写。如4月份为April
%c: 日期时间的字符串表示。(如: 04/07/10 10:43:39)
%d: 日在这个月中的天数(是这个月的第几天)
%f: 微秒(范围[0,999999])
%H: 小时(24小时制,[0, 23])
%I: 小时(12小时制,[0, 11])
%j: 日在年中的天数 [001,366](是当年的第几天)
%m: 月份([01,12])
%M: 分钟([00,59])
%p: AM或者PM
%S: 秒(范围为[00,61],为什么不是[00, 59],参考python手册~_~)
%U: 周在当年的周数当年的第几周),星期天作为周的第一天
%w: 今天在这周的天数,范围为[0, 6],6表示星期天
%W: 周在当年的周数(是当年的第几周),星期一作为周的第一天
%x: 日期字符串(如:04/07/10)
%X: 时间字符串(如:10:43:39)
%y: 2个数字表示的年份
%Y: 4个数字表示的年份
%z: 与utc时间的间隔 (如果是本地时间,返回空字符串)
%Z: 时区名称(如果是本地时间,返回空字符串)
%%: %% => %
例子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
|
这些就是datetime模块的基本内容,总算写完了~~oh yeah~~
更多Python模块学习 datetime介绍相关文章请关注PHP中文网!