1, Introduction to datetime module
(1) The datetime module contains the following classes:
Class name | Function description |
---|---|
date | Date object, common attributes are year, month, day |
time | Time object |
datetime | Date time object, commonly used attributes are hour, minute, second, microsecond |
datetime_CAPI | Date time Object C language interface |
timedelta | Time interval, that is, the length between two time points |
tzinfo | Time zone information object |
(2) , constants contained in the datetime module
constant | Function description | usage | Return value |
---|---|---|---|
MAXYEAR | Returns the maximum year that can be represented | datetime.MAXYEAR | 9999 |
MINYEAR | Returns the minimum year that can be represented | datetime.MINYEAR | 1 |
2, date class
(1) , date object composition
1. The date object consists of year, month and day
date(year,month,day)
2. The data descriptors of year, month and day can be accessed:
>>> a = datetime.date.today() >>> a datetime.date(2017, 3, 22) >>> a.year 2017 >>> a.month 3 >>> a.day 22
3. Of course, you can also get the above values using the \\\\\\\\
>>> a.__getattribute__('year') 2017 >>> a.__getattribute__('month') 3 >>> a.__getattribute__('day') 22
(2) Methods and properties contained in, date objects
1, Method for date comparison size
Method name | Method description | usage |
---|---|---|
__eq__(...) | Equal to (x==y) | x.__eq__(y) |
__ge__(...) | Greater than or equal to (x > = y) | x.__ge__(y) |
__gt__(...) | Greater than (x>y) | x.__gt__(y) |
__le__(...) | Less than or equal to (x < = y) | x.__le__(y) |
__lt__(...) | Less than (x | x.__lt__(y) |
__ne__(...) | Not equal to (x!=y) | x.__ne__(y) |
The return value of the above method is True\False
An example is as follows:
>>> a=datetime.date(2017,3,1) >>> b=datetime.date(2017,3,15) >>> a.__eq__(b) False >>> a.__ge__(b) False >>> a.__gt__(b) False >>> a.__le__(b) True >>> a.__lt__(b) True >>> a.__ne__(b) True
2. How many days is the difference between two dates
In fact, there is not much difference between the two methods, one is forward operation, the other is reverse operation
Method name | Method description | usage |
---|---|---|
__sub__(...) | x - y | x.__sub__(y) |
__rsub__(...) | y - x | x.__rsub__(y) |
An example is as follows:
>>> a datetime.date(2017, 3, 22) >>> b datetime.date(2017, 3, 15) >>> a.__sub__(b) datetime.timedelta(7) >>> a.__rsub__(b) datetime.timedelta(-7)
The return value type of the calculation result is datetime.timedelta. If you get the result of integer type, you can operate as follows:
>>> a.__sub__(b).days 7 >>> a.__rsub__(b).days -7
3. ISO standardization date
If you want to use a date that conforms to ISO standards, use the following three methods:
1) . * isocalendar(...) *: returns a tuple containing three values: year year, week number week, weekday week (Monday is 1 7 on Sunday):
Examples are as follows
>>> a = datetime.date(2017,3,22) >>> a.isocalendar() (2017, 12, 3) >>> a.isocalendar()[0] 2017 >>> a.isocalendar()[1] 12 >>> a.isocalendar()[2] 3 2). isoformat(...): returns a date string conforming to ISO 8601 standard (YYYY-MM-DD);
Examples are as follows
>>> a = datetime.date(2017,3,22) >>> a.isoformat() '2017-03-22'
3) . isoweekday(...): returns the number of weeks (Monday is 1) of a specified date that conforms to ISO standards 7 on Sunday)
An example is as follows:
>>> a = datetime.date(2017,3,22) >>> a.isoweekday() 3
4) Similar to isoweekday(...), there is also a weekday(...) method, except that the weekday(...) method returns 0 on Monday and 6 on Sunday
An example is as follows:
>>> a = datetime.date(2017,3,22) >>> a.weekday() 2
4. Other methods and properties
1) . timetuple(...): in order to be compatible with time.localtime(...), this method returns an array of type time.struct_time, but some element values related to time are 0:
>>> a = datetime.date(2017,3,22) >>> a.timetuple() time.struct_time(tm_year=2017, tm_mon=3, tm_mday=22, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=2, tm_yday=81, tm_isdst=-1) >>> a.timetuple().tm_year 2017 >>> a.timetuple().tm_mon 3 >>> a.timetuple().tm_mday 22
2) . toolbar (...): returns the number of days from the beginning of the Gregorian calendar to the present. January 1, A.D. 1
>>> a = datetime.date(2017,3,22) >>> a.toordinal() 736410
3) . replace(...): returns a new date object that replaces the specified date field. The three optional parameters are year, month and day. Note that the replacement is to generate a new object without affecting the original date object.
>>> a = datetime.date(2017,3,22) >>> b = a.replace(2017,2,28) >>> a datetime.date(2017, 3, 22) >>> b datetime.date(2017, 2, 28)
4) The. Resolution: Date object represents the minimum unit of date. This is the day.
>>> datetime.date.resolution datetime.timedelta(1)
5).fromordinal(...): convert Gregorian Calendar time to date object; Gregorian Calendar: a calendar representation method, similar to Chinese lunar calendar, which is widely used in western countries.
>>> a = datetime.date(2017,3,22) >>> b = a.toordinal() >>> datetime.date.fromordinal(b) datetime.date(2017, 3, 22)
6).fromtimestamp(...): returns a date object based on the given time kill
>>> time.time() 1490165087.2242179 >>> datetime.date.fromtimestamp(time.time()) datetime.date(2017, 3, 22)
7).today(...): returns the current date
>>> datetime.date.today() datetime.date(2017, 3, 22)
8).max: the maximum number of years, months, and days that the date class can represent
>>> datetime.date.max datetime.date(9999, 12, 31)
9).min: the minimum number of years, months, and days that the date class can represent
>>> datetime.date.min datetime.date(1, 1, 1)
(3) String output of,, date
1. If you want to convert a date object to a string object, you can use the \
>>> a = datetime.date(2017,3,22) >>> a.__format__('%Y-%m-%d') '2017-03-22' >>> a.__format__('%Y/%m/%d') '2017/03/22' >>> a.__format__('%y/%m/%d') '17/03/22' >>> a.__format__('%D') '03/22/17'
The equivalent method to this method is strftime(...)
>>> a.strftime("%Y%m%d") '20170322'
For information about formatting strings, please refer to the last: appendix: time and date formatting symbols in python
2. If it's just a simple str ing to get the date, use the
>>> a.__str__() '2017-03-22'
3. If you want to get the format of the ctime style, use ctime(...):
>>> a.ctime() 'Wed Mar 22 00:00:00 2017'
3, time class
(1) , data composition of time class
The time class consists of five parts: hour hour, minute, second second, microsecond and tzinfo
time([hour[, minute[, second[, microsecond[, tzinfo]]]]])
Accordingly, there are five variables in the time class to store the corresponding values:
>>> a = datetime.time(12,20,59,899) >>> a datetime.time(12, 20, 59, 899) >>> a.hour 12 >>> a.minute 20 >>> a.second 59 >>> a.microsecond 899 >>> a.tzinfo
Like the date class, the time class also contains the getattribute method to read related attributes:
>>> a.__getattribute__('hour') 12 >>> a.__getattribute__('minute') 20 >>> a.__getattribute__('second') 59
(2) , methods and properties in the time class
1. Compare time size
Related methods include: eq, ge, gt, le, lt, ne
The method here is the same as the method defined in the date class. The use method is the same as that of the date class. It is just introduced here. The example is as follows:
>>> a = datetime.time(12,20,59,899) >>> b = datetime.time(11,20,59,889) >>> a.__eq__(b) False >>> a.__ne__(b) True >>> a.__ge__(b) True >>> a.__gt__(b) True >>> a.__le__(b) False >>> a.__lt__(b) False
2,__nonzero__(...)
Judge whether the time object is non-zero, and the return value is True/False:
>>> a = datetime.time(12,20,59,899) >>> a.__nonzero__() True
3. Other properties
1) , max: maximum schedule value:
>>> datetime.time.max datetime.time(23, 59, 59, 999999)
2) min: minimum schedule indicator value
>>> datetime.time.min datetime.time(0, 0)
3) , resolution: time interval unit is minute
>>> datetime.time.resolution datetime.timedelta(0, 0, 1)
(3) , string output of time
1. If you want to convert a time object to a string object, you can use the \
>>> a = datetime.time(12,20,59,899) >>> a.__format__('%H:%M:%S') '12:20:59'
The equivalent method to this method is strftime(...)
>>> a = datetime.time(12,20,59,899) >>> a.strftime('%H:%M:%S') '12:20:59'
For information about formatting strings, please refer to the last: appendix: time and date formatting symbols in python
2. ISO standard output
If you want the output time character to conform to ISO standards, use isoformat(...):
>>> a = datetime.time(12,20,59,899) >>> a.isoformat() '12:20:59.000899'
3. If it's just a simple str ing to get the time, use \
>>> a = datetime.time(12,20,59,899) >>> a.__str__() '12:20:59.000899'
4, datetime class
(1) Data composition of datetime class
The date time class is actually a combination of the date class and the time class. Most of its methods and properties are inherited from these two classes. For related operation methods, please refer to the introduction of the two classes above. Its data structure is also composed of all the attributes of these two classes.
datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]])
(2) , methods and properties specific to datetime
1, date(… ): returns the date part of the datetime object:
>>> a = datetime.datetime.now() >>> a datetime.datetime(2017, 3, 22, 16, 9, 33, 494248) >>> a.date() datetime.date(2017, 3, 22)
2, time(... ): returns the time part of the datetime object:
>>> a = datetime.datetime.now() >>> a datetime.datetime(2017, 3, 22, 16, 9, 33, 494248) >>> a.time() datetime.time(16, 9, 33, 494248)
3,utctimetuple(… ): return UTC time tuple:
>>> a = datetime.datetime.now() >>> a datetime.datetime(2017, 3, 22, 16, 9, 33, 494248) >>> a.utctimetuple() time.struct_time(tm_year=2017, tm_mon=3, tm_mday=22, tm_hour=16, tm_min=9, tm_sec=33, tm_wday=2, tm_yday=81, tm_isdst=0)
4,combine(… ): merge a date object and a time object to generate a datetime object:
>>> a = datetime.datetime.now() >>> a datetime.datetime(2017, 3, 22, 16, 9, 33, 494248) >>>datetime.datetime.combine(a.date(),a.time()) datetime.datetime(2017, 3, 22, 16, 9, 33, 494248)
5, now(... ): returns the datetime object of the current datetime:
>>> a = datetime.datetime.now() >>> a datetime.datetime(2017, 3, 22, 16, 9, 33,
6,utcnow(… ): returns the UTC datetime object for the current datetime:
>>> a = datetime.datetime.utcnow() >>> a datetime.datetime(2017, 3, 22, 8, 26, 54, 935242)
7,strptime(… ): return a corresponding datetime object according to the two parameters of string and format:
>>> datetime.datetime.strptime('2017-3-22 15:25','%Y-%m-%d %H:%M') datetime.datetime(2017, 3, 22, 15, 25)
8,utcfromtimestamp(… ): datetime object of UTC timestamp with timestamp value of time.time():
>>> datetime.datetime.utcfromtimestamp(time.time()) datetime.datetime(2017, 3, 22, 8, 29, 7, 654272)
5, timedelta class
The timedelta class is used to calculate the difference between two datetime objects.
This class contains the following properties:
1. Days: days
2. Microseconds: microseconds (> = 0 and < 1 second)
3. Seconds: seconds (> = 0 and < 1 day)
6, Date calculation practice
1. Get the current date and time:
>>> now = datetime.datetime.now() >>> now datetime.datetime(2017, 3, 22, 16, 55, 49, 148233) >>> today = datetime.date.today() >>> today datetime.date(2017, 3, 22) >>> now.date() datetime.date(2017, 3, 22) >>> now.time() datetime.time(16, 55, 49, 148233)
2. Get the date of the first and last day of last month:
>>> today = datetime.date.today() >>> today datetime.date(2017, 3, 22) >>> mlast_day = datetime.date(today.year, today.month, 1) - datetime.timedelta(1) >>> mlast_day datetime.date(2017, 2, 28) >>> mfirst_day = datetime.date(mlast_day.year, mlast_day.month, 1) >>> mfirst_day datetime.date(2017, 2, 1)
3. Acquisition time difference
Time difference in seconds
>>> start_time = datetime.datetime.now() >>> end_time = datetime.datetime.now() >>> (end_time - start_time).seconds 7
The difference can be viewed not only in seconds, but also in days, seconds and microseconds
4. Calculate the time 8 hours after the current time
>>> d1 = datetime.datetime.now() >>> d2 = d1 + datetime.timedelta(hours = 8) >>> d2 datetime.datetime(2017, 3, 23, 1, 10, 37, 182240)
Can be calculated: days, hours, minutes, seconds, microseconds
5. Calculate the date of last Monday and Sunday
today = datetime.date.today() >>> today datetime.date(2017, 3, 23) >>> today_weekday = today.isoweekday() >>> last_sunday = today - datetime.timedelta(days=today_weekday) >>> last_monday = last_sunday - datetime.timedelta(days=6) >>> last_sunday datetime.date(2017, 3, 19) >>> last_monday datetime.date(2017, 3, 13)
6. Calculate the last day of the month and the number of days of the month
>>> date = datetime.date(2017,12,20) >>> def eomonth(date_object): ... if date_object.month == 12: ... next_month_first_date = datetime.date(date_object.year+1,1,1) ... else: ... next_month_first_date = datetime.date(date_object.year, date_object.month+1, 1) ... return next_month_first_date - datetime.timedelta(1) ... >>> eomonth(date) datetime.date(2017, 12, 31) >>> eomonth(date).day 31
7. Calculate the day of the next month of the specified date
Here we call the function eomonth(...) in the previous item
>>> date = datetime.date(2017,12,20) >>> def edate(date_object): ... if date_object.month == 12: ... next_month_date = datetime.date(date_object.year+1, 1,date_object.day) ... else: ... next_month_first_day = datetime.date(date_object.year,date_object.month+1,1) ... if date_object.day > eomonth(last_month_first_day).day: ... next_month_date = datetime.date(date_object.year,date_object.month+1,eomonth(last_month_first_day).day) ... else: ... next_month_date = datetime.date(date_object.year, date_object.month+1, date_object.day) ... return next_month_date ... >>> edate(date) datetime.date(2018, 1, 20)
8. Obtain the time period from Monday to today and the corresponding time period of last week
>>> today = datetime.date.today() >>> this_monday = today - datetime.timedelta(today.isoweekday()-1) >>> last_monday = this_monday - datetime.timedelta(7) >>> last_weekday = today -datetime.timedelta(7) >>> this_monday datetime.date(2017, 3, 20) >>> today datetime.date(2017, 3, 23) >>> last_monday datetime.date(2017, 3, 13) >>> last_weekday datetime.date(2017, 3, 16)
Appendix: time and date format symbols in python:
Symbol | Explain |
---|---|
%y | Two digit year representation (00-99) |
%Y | Four digit year representation (000-9999) |
%m | Month (01-12) |
%d | Day of the month (0-31) |
%H | 24 hours (0-23) |
%I | 12 hour hours (01-12) |
%M | Minutes (00 = 59) |
%S | Seconds (00-59) |
%a | Local simplified week name |
%A | Local full week name |
%b | Local simplified month name |
%B | Local full month name |
%c | Local corresponding date and time representation |
%j | One day of the year (001-366) |
%p | Local A.M. or P.M. equivalent |
%U | Weeks of the year (00-53) Sunday is the beginning of the week |
%w | Week (0-6), Sunday is the beginning of the week |
%W | Weeks of the year (00-53) Monday is the beginning of the week |
%x | Local corresponding date representation |
%X | Local corresponding time representation |
%Z | Name of the current time zone |
%% | % number itself |