Home > Article > Backend Development > Datetime module reference manual in Python
Preface
Python provides multiple built-in modules for manipulating date and time, such as calendar, time, and datetime. The interface provided by the time module is basically consistent with the C standard library time.h. Compared with the time module, the interface of the datetime module is more intuitive and easier to call.
The module defines two constants:
datetime.MINYEAR
datetime.MAXYEAR
These two constants respectively represent what datetime can represent The minimum and maximum year. Among them, MINYEAR = 1, MAXYEAR = 9999.
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 zones.
Note: The types of objects listed above are all immutable.
date class
The date class represents a date (composed of year, month, day), and its prototype is as follows:
class datetime.date(year, month , day)
Parameter description: 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:
date.max, date.min: what the date object can represent Maximum and minimum dates;
date.resolution: The date object represents the smallest 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 to 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.)
Usage example:
>>> datetime.date.max datetime.date(9999, 12, 31) >>> datetime.date.min datetime.date(1, 1, 1) >>> datetime.date.resolution datetime.timedelta(1) >>> datetime.date.today() datetime.date(2016, 5, 12) >>> datetime.date.fromtimestamp(time.time()) datetime.date(2016, 5, 12)
Instance methods and properties provided by date:
date.year, date. month, date.day: year, month, day;
date.replace(year, month, day): Generate a new date object, replacing the original object with the year, month, and day specified by the parameters properties. (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, return 1; if it is Tuesday, return 2, and so on;
date.isocalendar(): Return a tuple in the format of (year, month, day);
date.isoformat(): Returns a string in the format of 'YYYY-MM-DD';
date.strftime(fmt): Custom format string.
Usage example:
>>> today = datetime.date.today() >>> today.year 2016 >>> today.month 5 >>> today.day 12 >>> tomorrow = today.replace(day=13) >>> tomorrow datetime.date(2016, 5, 13) >>> tomorrow.timetuple() time.struct_time(tm_year=2016, tm_mon=5, tm_mday=13, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=4, tm_yday=134, tm_isdst=-1) >>> tomorrow.toordinal() 736097 >>> tomorrow.weekday() 4 >>> tomorrow.isoweekday() 5 >>> tomorrow.isocalendar() (2016, 19, 5) >>> tomorrow.isoformat() '2016-05-13' >>> tomorrow.strftime("%y-%m-%d") '16-05-13'
date overloads the simple operator:
date allows for dates Perform additions, subtractions and comparisons:
date2 = date1 + timedelta:
Date plus an interval, returning a new date object
date2 = date1 - timedelta :
Dates are separated by intervals and a new date object is returned
timedelta = date1 - date2:
Subtract two dates and return one Time interval object
date1 < date2:
Compare two dates.
Usage example:
>>> now = datetime.date.today() >>> now datetime.date(2016, 5, 12) >>> now += datetime.date.resolution >>> now datetime.date(2016, 5, 13) >>> now -= datetime.date.resolution >>> now datetime.date(2016, 5, 12) >>> now < datetime.date.max True
Time class
The time class represents time (consisting of hours, minutes, seconds and microseconds Composition), its prototype is as follows:
class datetime.time(hour=0, minute=0, second=0, microsecond=0, tzinfo=None)
Parameter description: The range of
hour is [0, 24), the range of
minute is [0, 60), the range of
second is [0, 60),
The range of microsecond is [0, 1000000),
tzinfo represents time zone information.
Class attributes defined by the time class:
time.min, time.max: the minimum and maximum time that the time class can represent. Among them, time.min = time(0, 0, 0, 0), time.max = time(23, 59, 59, 999999);
time.resolution: The smallest unit of time, here is 1 Microseconds;
Usage example:
>>> datetime.time.min datetime.time(0, 0) >>> datetime.time.max datetime.time(23, 59, 59, 999999) >>> datetime.time.resolution datetime.timedelta(0, 0, 1)
Instance methods and properties provided by the time class:
time .hour, time.minute, time.second, time.microsecond: hours, minutes, seconds, microseconds;
time.tzinfo: time zone information;
time.replace([hour[ , minute[, second[, microsecond[, tzinfo]]]]]): Create a new time object and replace the attributes in the original object with the hours, minutes, seconds, and microseconds specified by the parameters (the original object remains unchanged);
time.isoformat(): Returns a string representation in the format of "HH:MM:SS";
time.strftime(fmt): Returns a custom format String.
Usage example:
>>> tm = datetime.time(18, 18, 18) >>> tm.hour 18 >>> tm.minute 18 >>> tm.second 18 >>> tm.microsecond 0 >>> tm.tzinfo >>> tm.isoformat() '18:18:18' >>> tm.replace(hour=20) datetime.time(20, 18, 18) >>> tm.strftime("%I:%M:%S %p") '06:18:18 PM'
Objects of the time class can only be compared and cannot be added or subtracted.
Datetime class
Datetime is a combination of date and time, including all information of date and time. Its prototype is as follows:
class datetime.datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None)
各参数的含义与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对象,data 与 time 类没有提供该方法。
使用示例:
>>> datetime.datetime.min datetime.datetime(1, 1, 1, 0, 0) >>> datetime.datetime.max datetime.datetime(9999, 12, 31, 23, 59, 59, 999999) >>> datetime.datetime.resolution datetime.timedelta(0, 0, 1) >>> print datetime.datetime.resolution 0:00:00.000001 >>> today = datetime.datetime.today() >>> today datetime.datetime(2016, 5, 12, 12, 46, 47, 246240) >>> datetime.datetime.now() datetime.datetime(2016, 5, 12, 12, 47, 9, 850643) >>> datetime.datetime.utcnow() datetime.datetime(2016, 5, 12, 4, 47, 42, 188124) >>> datetime.datetime.fromtimestamp(time.time()) datetime.datetime(2016, 5, 12, 12, 48, 40, 459676) >>> datetime.datetime.combine(datetime.date(1990, 10, 05), datetime.time(18, 18, 18)) datetime.datetime(1990, 10, 5, 18, 18, 18) >>> datetime.datetime.strptime("2010-04-07 01:48:16.234000", "%Y-%m-%d %H:%M:%S .%f") datetime.datetime(2010, 4, 7, 1, 48, 16, 234000)
datetime 的实例方法与属性
datetime类提供的实例方法与属性大部分功能与 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)
datetime 对象同样可以进行比较,或者相减返回一个时间间隔对象,或者日期时间加上一个间隔返回一个新的日期时间对象。
timedelta 类
datetime.timedelta 对象代表两个时间之间的的时间差,两个 date 或 datetime 对象相减时可以返回一个timedelta 对象。其原型如下:
class datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)
所有参数可选,且默认都是0,参数的值可以是整数,浮点数,正数或负数。
内部只存储days,seconds,microseconds,其他参数的值会自动按如下规则抓转换:
1 millisecond(毫秒) 转换成 1000 microseconds(微秒)
1 minute 转换成 60 seconds
1 hour 转换成 3600 seconds
1 week转换成 7 days
三个参数的取值范围分别为:
0 <= microseconds < 1000000
0 <= seconds < 3600*24 (the number of seconds in one day)
-999999999 <= days <= 999999999
timedelta 类定义的类属性:
timedelta.min:时间间隔对象的最小值,即 timedelta(-999999999).
timedelta.max:时间间隔对象的最大值,即 timedelta(days=999999999, hours=23, minutes=59, seconds=59, microseconds=999999).
timedelta.resolution:时间间隔的最小单位,即 timedelta(microseconds=1).
使用示例:
>>> datetime.timedelta.min datetime.timedelta(-999999999) >>> datetime.timedelta.max datetime.timedelta(999999999, 86399, 999999) >>> datetime.timedelta.resolution datetime.timedelta(0, 0, 1) >>> print datetime.timedelta.resolution 0:00:00.000001
timedelta 实例方法
timedelta.total_seconds():计算时间间隔的总秒数
使用示例:
>>> datetime.timedelta.resolution.total_seconds() 1e-06
格式字符串
datetime、date、time 都提供了 strftime() 方法,该方法接收一个格式字符串,输出日期时间的字符串表示。支持的转换格式如下:
%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.datetime.now() >>> dt.strftime('%Y-%m-%d %H:%M:%S %f') '2016-05-12 14:19:22 333943' >>> dt.strftime('%y-%m-%d %I:%M:%S %p') '16-05-12 02:19:22 PM' >>> dt.strftime("%a") 'Thu' >>> dt.strftime("%A") 'Thursday' >>> dt.strftime("%b") 'May' >>> dt.strftime("%B") 'May' >>> dt.strftime("%c") 'Thu May 12 14:19:22 2016' >>> dt.strftime("%x") '05/12/16' >>> dt.strftime("%X") '14:19:22' >>> dt.strftime("%w") '4' >>> dt.strftime("%j") '133' >>> dt.strftime("%u") '4' >>> dt.strftime("%U") '19'
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流。
更多Python中datetime模块参考手册相关文章请关注PHP中文网!