Home > Backend Development > Python Tutorial > Python module learning datetime introduction

Python module learning datetime introduction

高洛峰
Release: 2017-01-14 15:52:28
Original
1071 people have browsed it

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:

from datetime import * 
import time 

print 'date.max:', date.max 
print 'date.min:', date.min 
print 'date.today():', date.today() 
print 'date.fromtimestamp():', date.fromtimestamp(time.time()) 

# # ---- 结果 ---- 
# date.max: 9999-12-31 
# date.min: 0001-01-01 
# date.today(): 2010-04-06 
# date.fromtimestamp(): 2010-04-06
Copy after login

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:

now = date(2010, 04, 06) 
tomorrow = now.replace(day = 07) 
print 'now:', now, ', tomorrow:', tomorrow 
print 'timetuple():', now.timetuple() 
print 'weekday():', now.weekday() 
print 'isoweekday():', now.isoweekday() 
print 'isocalendar():', now.isocalendar() 
print 'isoformat():', now.isoformat() 

# # ---- 结果 ---- 
# now: 2010-04-06 , tomorrow: 2010-04-07 
# timetuple(): (2010, 4, 6, 0, 0, 0, 1, 96, -1) 
# weekday(): 1 
# isoweekday(): 2 
# isocalendar(): (2010, 14, 2) 
# isoformat(): 2010-04-06
Copy after login

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:

now = date.today() 
tomorrow = now.replace(day = 7) 
delta = tomorrow - now 
print &#39;now:&#39;, now, &#39; tomorrow:&#39;, tomorrow 
print &#39;timedelta:&#39;, delta 
print now + delta 
print tomorrow > now 

# # ---- 结果 ---- 
# now: 2010-04-06 tomorrow: 2010-04-07 
# timedelta: 1 day, 0:00:00 
# 2010-04-07 
# True
Copy after login

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):返回自定义格式化字符串。在下面详细介绍;

使用例子:

from datetime import * 
tm = time(23, 46, 10) 
print &#39;tm:&#39;, tm 
print &#39;hour: %d, minute: %d, second: %d, microsecond: %d&#39; / 
% (tm.hour, tm.minute, tm.second, tm.microsecond) 
tm1 = tm.replace(hour = 20) 
print &#39;tm1:&#39;, tm1 
print &#39;isoformat():&#39;, tm.isoformat() 

# # ---- 结果 ---- 
# tm: 23:46:10 
# hour: 23, minute: 46, second: 10, microsecond: 0 
# tm1: 20:46:10 
# isoformat(): 23:46:10
Copy after login

像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对象;

使用例子:

from datetime import * 
import time 

print &#39;datetime.max:&#39;, datetime.max 
print &#39;datetime.min:&#39;, datetime.min 
print &#39;datetime.resolution:&#39;, datetime.resolution 
print &#39;today():&#39;, datetime.today() 
print &#39;now():&#39;, datetime.now() 
print &#39;utcnow():&#39;, datetime.utcnow() 
print &#39;fromtimestamp(tmstmp):&#39;, datetime.fromtimestamp(time.time()) 
print &#39;utcfromtimestamp(tmstmp):&#39;, datetime.utcfromtimestamp(time.time()) 

# ---- 结果 ---- 
# datetime.max: 9999-12-31 23:59:59.999999 
# datetime.min: 0001-01-01 00:00:00 
# datetime.resolution: 0:00:00.000001 
# today(): 2010-04-07 09:48:16.234000 
# now(): 2010-04-07 09:48:16.234000 
# utcnow(): 2010-04-07 01:48:16.234000 # 中国位于+8时间,与本地时间相差8 
# fromtimestamp(tmstmp): 2010-04-07 09:48:16.234000 
# utcfromtimestamp(tmstmp): 2010-04-07 01:48:16.234000
Copy after login

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: 时区名称(如果是本地时间,返回空字符串)
%%: %% => %

例子:

dt = datetime.now() 
print &#39;(%Y-%m-%d %H:%M:%S %f): &#39;, dt.strftime(&#39;%Y-%m-%d %H:%M:%S %f&#39;) 
print &#39;(%Y-%m-%d %H:%M:%S %p): &#39;, dt.strftime(&#39;%y-%m-%d %I:%M:%S %p&#39;) 
print &#39;%%a: %s &#39; % dt.strftime(&#39;%a&#39;) 
print &#39;%%A: %s &#39; % dt.strftime(&#39;%A&#39;) 
print &#39;%%b: %s &#39; % dt.strftime(&#39;%b&#39;) 
print &#39;%%B: %s &#39; % dt.strftime(&#39;%B&#39;) 
print &#39;日期时间%%c: %s &#39; % dt.strftime(&#39;%c&#39;) 
print &#39;日期%%x:%s &#39; % dt.strftime(&#39;%x&#39;) 
print &#39;时间%%X:%s &#39; % dt.strftime(&#39;%X&#39;) 
print &#39;今天是这周的第%s天 &#39; % dt.strftime(&#39;%w&#39;) 
print &#39;今天是今年的第%s天 &#39; % dt.strftime(&#39;%j&#39;) 
print &#39;今周是今年的第%s周 &#39; % dt.strftime(&#39;%U&#39;) 

# # ---- 结果 ---- 
# (%Y-%m-%d %H:%M:%S %f): 2010-04-07 10:52:18 937000 
# (%Y-%m-%d %H:%M:%S %p): 10-04-07 10:52:18 AM 
# %a: Wed 
# %A: Wednesday 
# %b: Apr 
# %B: April 
# 日期时间%c: 04/07/10 10:52:18 
# 日期%x:04/07/10 
# 时间%X:10:52:18 
# 今天是这周的第3天 
# 今天是今年的第097天 
# 今周是今年的第14周
Copy after login

这些就是datetime模块的基本内容,总算写完了~~oh yeah~~

更多Python模块学习 datetime介绍相关文章请关注PHP中文网!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template