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

Python module learning datetime introduction

高洛峰
高洛峰Original
2017-01-14 15:52:281090browse

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

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

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 634d73ca602ef132e3a192b6099e13df % 

例子: 

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

# # ---- 结果 ---- 
# (%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周

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

更多Python模块学习 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